In HTML, name="object[prop]" doesn't seem to work - javascript

When I console.log the req.body it gives me:
[Object: null prototype] {
'shoe[name]': 'Shoe Name',
'shoe[description]': '',
'shoe[pictures]': '',
'shoe[collections]': 'Shoe Collection'
}
But when I console.log req.body.shoe It prints undefined,
been breaking my head for a few days now
The form:
<form action="/shoes/" method="post">
<input type="text" name="shoe[name]" placeholder="Name of the shoe">
<textarea name="shoe[description]" cols="30" rows="10"></textarea>
<input type="file" name="shoe[pictures]">
<input type="text" name="shoe[collections]">
<input type="submit" value="Post the Shoe">
</form>
Shoe Model:
const mongoose = require('mongoose');
const shoeSchema = new mongoose.Schema({
name: { type: String, unique: true },
description: String,
displayPicture: mongoose.Schema.Types.ObjectId,
pictures: [ { type: mongoose.Schema.Types.ObjectId } ],
collections: [ { type: mongoose.Schema.Types.ObjectId, unique: true } ],
dateOfPublish: { type: Date, default: Date.now },
comments: [
{
userId: { type: mongoose.Schema.Types.ObjectId, unique: true, ref: 'Comment' }
}
]
});
module.exports = mongoose.model('Shoe', shoeSchema);
Node.js + Express create route:
//Create
router.post('/', (req, res) => {
console.log(req.body.shoe);
Shoe.create(req.body.shoe, (err, shoe) => {
if (err) {
console.log(err);
} else {
return res.redirect('/');
}
});
});

You cannot implement the below way the html part
<input type="file" name="shoe[pictures]">
You yourself is seeing that
[Object: null prototype] {
'shoe[name]': 'Shoe Name',
'shoe[description]': '',
'shoe[pictures]': '',
'shoe[collections]': 'Shoe Collection'
}
'shoe[pictures]' is the entire key and you are only accessing req.body.shoe
First your entire HTML need to be changed.
<form action="/shoes/" method="post">
<input type="text" name="name" placeholder="Name of the shoe">
<textarea name="description" cols="30" rows="10"></textarea>
<input type="file" name="pictures">
<input type="text" name="collections">
<input type="submit" value="Post the Shoe">
</form>
And then in backend in req.body object you will receive all the properties name,description,pictures,collections
After that you can access
req.body.name
req.body.description etc
Then in backend you need to define
var shoe = {...req.body}
and then you can use shoe object

<% include ../partials/header %>
<div class="row">
<div class="col-md-4">
<h2><%= user.firstName + " " + user.lastName %></h2>
<div class="thumbnail">
<img src="<%= user.avatar %>" alt="user profile image">
<div class="caption"><%= user.email %></div>
</div>
</div>
<div class="col-md-8">
``` <h3><%= user.username %>'s campgrounds</h3>
<% campgrounds.forEach(campground => { %>
<div class="col-md-4 col-sm-6">
<div class="thumbnail card">
<img src="<%= campground.image.url %>" alt="<%= campground.name %>">
<div class="caption">
<h4 class="caption"><%= campground.name %></h4>
</div>
</div>
</div>
<% }); %>
</ul>
</div>
Edit Profile
</div>
<% include ../partials/footer %>
Can you see that %include is written here. if that statement is not present in your code it will not work. That is what i am trying to explain from that time
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Shoe</title>
</head>
<body>
<form action="/shoes/" method="post">
<input type="text" name="shoe[name]" placeholder="Name of the shoe">
<textarea name="shoe[description]" cols="30" rows="10"></textarea>
<input type="file" name="shoe[pictures]" value="Shoe Pictures">
<!-- tick the display pic -->
<input type="text" name="shoe[collections]">
<input type="submit" value="Post the Shoe">
</form>
</body>
</html>
In your there is nothing like that

The problem was with the body-parser, needed to use the qs library (true) instead of querystring(false) in the following line:
app.use(require('body-parser').urlencoded({ extended: true }));
originally extended was set to false.
for more info refer to this link

Related

how to insert array of objects in mongodb using express js

i want to insert my form data as an array of multiple objects.
how can i acheive this ..?
in below code only one object is inserted but i want to insert multiple objects that was described in mongoose schema.
i research a lot to do this but cant get success. please help me to acheive this.
i already acheive this in php but unable to do this in express.
[here is the code][1]
My Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css" integrity="sha512-XWTTruHZEYJsxV3W/lSXG1n3Q39YIWOstqvmFsdNEEQfHoZ6vm6E9GK2OrF6DSJSpIbRbi+Nn0WDPID9O7xB2Q==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/js/bootstrap.bundle.min.js" integrity="sha512-9GacT4119eY3AcosfWtHMsT5JyZudrexyEVzTBWV3viP/YfB9e2pEy3N7WXL3SV6ASXpTU0vzzSxsbfsuUH4sQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/js/bootstrap.min.js" integrity="sha512-8Y8eGK92dzouwpROIppwr+0kPauu0qqtnzZZNEF8Pat5tuRNJxJXCkbQfJ0HlUG3y1HB3z18CSKmUo7i2zcPpg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<script>
function remove_more(id) {
alertify.confirm('One Point ', 'Are you sure want to delete !', function () {
$('#box' + id).fadeOut(600, function () {
$('#box' + id).remove();
});
}, function () {
alertify.error('Cancel')
});
}
</script>
<div class="container my-5">
<form action="/add" method="post">
<input type="text" name="name" id="">
<input type="email" name="email" id="">
<div id="attributeBox" class="mb-3">
<div class="form-group row">
<div class="col-sm-5">
<label for="price" class="col-sm-3 control-label col-form-label">Price</label>
<input type="text" class="form-control" name="price[]" id="price">
</div>
<div class="col-sm-5">
<label for="qty" class="col-sm-3 control-label col-form-label">Qty</label>
<input type="text" class="form-control" name="qty[]" id="qty">
</div>
<div class="col-sm-2 mt-4 d-flex-align-item-center ">
<button type="button" id="Addattribute" class="btn btn-warning btn-sm"><i
class="fa fa-plus"></i></button>
</div>
</div>
</div>
<input type="hidden" id="numattribute" value="1">
<input type="submit" value="Submit">
</form>
</div>
<script>
$('#Addattribute').click(function (e) {
e.preventDefault();
var numattribute = jQuery('#numattribute').val();
numattribute++;
jQuery('#numattribute').val(numattribute);
var html1 = '<div id="box' + numattribute + '"><div class="form-group row"><div class="col-sm-5"><label for="price" class="col-sm-3 control-label col-form-label">Price</label><input type="text" class="form-control" name="price[]" id="price"></div><div class="col-sm-5"><label for="qty" class="col-sm-3 control-label col-form-label">Qty</label><input type="text" class="form-control" name="qty[]" id="qty"></div><div class="col-sm-2 mt-4 d-flex-align-item-center "><button type="button" id="Addattribute" class="btn btn-danger btn-sm float-right" onclick="remove_more(' + numattribute + ')"><i class="fa fa-trash"></i></button></div></div></div>'
jQuery('#attributeBox').append(html1);
});
</script>
</body>
</html>
mongoose schema
const mongoose = require("mongoose");
const { Schema } = mongoose;
const usersSchema = new Schema({
name: {
type: String,
required: [true, "Name is Required"],
},
email: {
type: String,
required: [true, "Email is Required"],
},
attributes: [
{
qty: { type: String, default: 1 },
price: { type: String, default: 1 },
},
],
created: {
type: Date,
required: true,
default: Date.now,
},
});
const user = mongoose.model("user", usersSchema);
user.createIndexes();
module.exports = user;
Add User API post
router.post("/add", urlencodedParser, async (req, res, next) => {
// An array of keys
var keys = req.body.qty;
// An array of values
var values = req.body.price;
// Map created
var map = new Map();
// Using loop to insert key
// value in map
for (var i = 0; i < keys.length; i++) {
map.set(keys[i], values[i]);
}
// Printing
for (var key of map.keys()) {
console.log(key + " => " + map.get(key));
}
const user = new User({
name: req.body.name,
email: req.body.email,
attributes: [
{
qty: key,
price: map.get(key),
},
],
});
console.log(user);
await user.save((err) => {
if (err) {
res.json({ message: err.message, type: "error" });
} else {
res.redirect("/");
}
});
});
my form has multiple fields

.save() function not working to update database

I have this working for a different Schema (I can show this code if needed) but when I tried to recreate it for another, it won't update my DB. It's connected to a MongoDB database and this functionality works with another Schema but this one does not
I've hit a dead end and have no idea a this point... Any help would be appreciated!!
Here is the POST controller
console.log("post");
const userId = req.body.userId;
const updatedName = req.body.name;
const updatedPassword = req.body.password;
const updatedEmail = req.body.email;
const updatedSkype = req.body.skype;
const updatedDepartment = req.body.department;
const updatedJobtitle = req.body.jobtitle;
const updatedLinemanager = req.body.linemanager;
const updatedNinumber = req.body.ninumber;
// const updatedJoinDate = req.body.joindate;
// console.log(req.body);
User.findById(userId)
.then((user) => {
isadmin = user.isadmin;
name = updatedName;
password = updatedPassword;
email = updatedEmail;
skype = updatedSkype;
department = updatedDepartment;
jobtitle = updatedJobtitle;
linemanager = updatedLinemanager;
ninumber = updatedNinumber;
joindate = user.joindate;
return user.save();
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));
};
The User model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
isadmin: {
type: Boolean,
required: true,
},
name: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
skype: {
type: String,
required: true,
},
department: {
type: String,
required: true,
},
jobtitle: {
type: String,
required: true,
},
linemanager: {
type: String,
required: true,
},
ninumber: {
type: String,
required: true,
},
joindate: {
type: Date,
required: true,
},
});
module.exports = mongoose.model("User", userSchema);
The Routes
router.get("/add-user", adminController.getAddUser);
router.get("/edit-user/:userId", adminController.getEditUser);
router.get("/edit-user-list", adminController.getEditUserList);
//POST USER
router.post("/add-user", adminController.postAddUser);
router.post("/edit-user/edit-user", adminController.postEditUser);
router.post("/edit-user", adminController.postEditUser);
router.post("/destroy-user", adminController.postDeleteUser);
And the HTML/EJS file
<%- include('../includes/head.ejs') %>
<link rel="stylesheet" href="/css/admin.css" />
<link rel="stylesheet" href="/css/add-user.css" />
<body>
<img src="pozzani.png" alt="pozzani logo" class="pozzanilogo" />
<div class="mainbackground">
<div class="leftcolumn">
<%- include('../includes/signout.ejs') %>
<%- include('../includes/nav.ejs') %>
<%- include('../includes/useful.ejs') %>
</div>
<div class="admin-column">
<h2 class="importanttitle">EDIT USER</h2>
<div class="update-container">
<h3 class="admin-title">Welcome to the USER edit tool</h3>
<p class="admin-content">Please edit forms below to make change. <b>ALL EDITS ARE FINAL!</b></p>
<form class="user-form" action="edit-user" method="POST">
<div class="form-section">
<label for="isadmin">Is Admin?</label>
<select id="isadmin" name="isadmin">
<% if (!user.isadmin) { %>
<option value="false" selected>False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="true">True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } else { %>
<option value="true" selected>True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } %>
</select>
</div>
<div class="form-section">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="<%= user.name %>" >
</div>
<div class="form-section">
<label for="password">Password</label>
<input type="text" name="password" id="password" value="<%= user.password %>">
</div>
<div class="form-section">
<label for="email">Email</label>
<input type="email" name="email" id="email" value="<%= user.email %>">
</div>
<div class="form-section">
<label for="skype">Skype</label>
<input type="text" name="skype" id="skype" value="<%= user.skype %>">
</div>
<div class="form-section">
<label for="department">Department</label>
<input type="text" name="department" id="department" value="<%= user.department %>">
</div>
<div class="form-section">
<label for="jobtitle">Job Title</label>
<input type="text" name="jobtitle" id="jobtitle" value="<%= user.jobtitle %>">
</div>
<div class="form-section">
<label for="linemanager">Line Manager</label>
<input type="text" name="linemanager" id="linemanager" value="<%= user.linemanager %>">
</div>
<div class="form-section">
<label for="ninumber">National Insurance Number</label>
<input type="text" name="ninumber" id="ninumber" value="<%= user.ninumber %>">
</div>
<!-- <div class="form-section">
<label for="joindate">Join Date</label>
<input type="date" name="joindate" id="joindate" value="<%= user.joindate %>">
</div> -->
<input type="hidden" value="<%= user._id %>" name="userId">
<button class="admin-btn" type="submit"><% userId = user._id %>Edit User</button>
</form>
</div>
</div>
</div>
</body>
</html>
Please use findByIdAndUpdate() function instead of findById() and save()
for example;
User.findByIdAndUpdate(userId, {
isadmin: user.isadmin,
name: updatedName,
...
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));

Can't read the form elements

I can't get the values of these three fields; it only returns an empty value (a space).
The ids are correctly set in the form.
<script>
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
function myFunction(){
const http = new easyHTTP;
http.put('https://otg0gf6qw5.execute-api.us-east-2.amazonaws.com/books',
data, function(err, post){
if(err) {
console.log(err);
} else {
console.log(post);
}
});
</script>
<!DOCTYPE html>
<html>
<body>
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<h1>Insert Book</h1>
<div class="field">
<label for="id">ID Book:</label>
<input type="text" id="idbook" name="id"/>
<small></small>
</div>
<div class="field">
<label for="id">Name Book:</label>
<input type="text" id="namebook" name="nameBook"/>
<small></small>
</div>
<div class="field">
<label for="id">Price Book:</label>
<input type="text" id="pricebook" name="priceBook"/>
<small></small>
</div>
<div class="field">
<button type="submit" class="full">SAVE BOOK</button>
</div>
</form>
</div>
When I enter the values, and click on SAVE I get an empty json, i.e .:
{"id":"","name":"","price":""}
with error:
"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: id"
The problem is that you are getting the values from the input fields as soon as the script runs, so you will get empty strings because the inputs at that point are empty.
To get the input values after the form is submitted, put the data variable inside the myFunction() method, it's important to read the values right before sending the data.
Example
<script>
function myFunction() {
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
const http = new easyHTTP;
http.put('https://otg0gf6qw5.execute-api.us-east-2.amazonaws.com/books', data, function(err, post) {
if(err) {
console.log(err);
} else {
console.log(post);
}
});
};
</script>
I don't know if this is what you mean, but I did let the data save in the console log when you press submit
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<h1>Insert Book</h1>
<div class="field">
<label for="id">ID Book:</label>
<input type="text" id="idbook" name="id"/>
<small></small>
</div>
<div class="field">
<label for="id">Name Book:</label>
<input type="text" id="namebook" name="nameBook"/>
<small></small>
</div>
<div class="field">
<label for="id">Price Book:</label>
<input type="text" id="pricebook" name="priceBook"/>
<small></small>
</div>
<div class="field">
<button type="submit" class="full">SAVE BOOK</button>
</div>
</form>
<script>
function myFunction(){
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
console.log(data);
}
</script>
</div></body></html>

Not submit data in mongodb database

Here i tried to store form data in my mongodb database(mongodb compass).
but after submit when i check than there are nothing in my database.
when i press sign up button than it's show me just curly brackets.
App.js file(main file)
const express = require("express");
const app = express();
const port = 8081;
require('./db/conn');
const path = require("path");
const hbs = require("hbs");
const register = require("./models/register");
const static_path = path.join(__dirname,"../public");
const template_path = path.join(__dirname,"../templates/views");
const partials_path = path.join(__dirname,"../templates/partials");
app.set("views",template_path);
app.set("view engine","hbs");
hbs.registerPartials(partials_path);
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.get("/",(req,res)=>{
res.render("signup");
})
app.get("/signup",(req,res)=>{
res.render("index");
})
app.get("/register",(req,res)=>{
res.render("register");
})
app.post("/register",async(req,res)=>{
try{
const password = req.body.password;
const cpassword = req.body.cpassword;
if(password===cpassword){
const registerEmployee = new Register({
firstname : req.body.firstname,
lastname : req.body.lastname,
email : req.body.email,
phone : req.body.phone,
age : req.body.age,
password: req.body.password,
})
const registered = await registerEmployee.save();
console.log(registered);
}
else{
res.send("password not matched");
}
res.send(registered);
}catch(error){
res.status(404).send(error)
}
})
app.listen(port,()=>{
console.log("succesfully port");
})
register.js file(here i define mongoose.schema file)
const mongoose = require("mongoose");
const employeeSchema = mongoose.Schema({
firstname :{
type:String,
required:true,
},
lastname:{
type:String,
required:true,
},
email:{
type:String,
required:true,
unique:true,
},
phone:{
type:Number,
required:true,
unique:true,
},
age:{
type:Number,
required:true,
},
password:{
type:String,
required:true,
},
})
const Register = new mongoose.model("register",employeeSchema);
module.exports = Register;
signup.hbs file(html form)
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/signin.css">
<title>Create New Account</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous">
</script>
<div class="signin-form">
<form action="/register" method="POST">
<div class="form-header">
<h2>Sign Up</h2>
<h2>Fill out this form and start chatting with your friends.</h2><br>
</div>
<div class="form-group">
<br>
<lable>firstname</lable>
<input type="text" class="form-control" name="firstname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>lastname</lable>
<input type="text" class="form-control" name="lastname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>email Address</lable>
<input type="text" class="form-control" name="email" placeholder="someone#site.com" />
</div>
<div class="form-group">
<br>
<lable>phone Number</lable>
<input type="text" class="form-control" name="phone" placeholder="contact number" />
</div>
<div class="form-group">
<br>
<lable>Age</lable>
<input type="number" class="form-control" name="age" placeholder="age" />
</div>
<div class="form-group">
<label> Password </label>
<input type="text" class="form-control" name="password" placeholder="password" />
</div>
<div class="form-group">
<label>Confirm Password </label>
<input type="text" class="form-control" name="cpassword" placeholder="confirm password" />
</div>
<input type="checkbox" class="checkbox-inline" /> <label>i accept terms and condition</label>
<div class="form-group">
<button class="btn btn-primary btn-block btn-lg " name="sign_up">Sign_Up</button>
</div>
</form>
<div class="text-center small" style="color:#67428B;"> Already have an Account ?Login </div>
</div>
</body>
</html>
try to put new before mongoose.Schema :
const employeeSchema = new mongoose.Schema
after so much time i solved error successfully, so i think i want to write here
here you can see in app file 7th line
const register = require("./models/register");
and when i enter new data then i use Register instead of register so there are an error.
const registerEmployee = new Register

How to create self referencing MongoDB schema and post routes using nodejs?

I am trying to create parent-child like nested system where child has same schema as of parent.Below is my parent schema, here children refers to the parentSchema again,
var mongoose = require("mongoose");
var parentSchema = new mongoose.Schema({
name: String,
children:[
{
ref: this
}
],
});
module.exports = mongoose.model("Parent", parentSchema);
Routes looks like this
app.get("/", function(req, res){
Parent.find({}).populate("children").exec(function(err, allParents){
if(err){
console.log(err);
}else{
res.render("index",{parents: allParents});
}
});
});
app.post("/", function(req,res){
var name = req.body.name;
var desc = req.body.desc;
var newParent = {name: name, description: desc}
Parent.create(newParent, function(err, newlyCreate){
if(err){
console.log(err);
}else{
res.redirect("/");
}
});
});
app.post("/:id", function(req, res){
Parent.findById(req.params.id, function(err, parent){
if(err){
console.log(err);
res.redirect("/");
}else{
parent.children.push(req.body.child);
parent.save();
console.log(parent.children);
res.redirect("/");
}
});
});
The problem is when I send data from form to post route it prints it but after pushing it into parent.children and then printing parent.children is shows null. Where is the problem???
EJS page looks like below:-
<form action="/" method="POST">
<div class="form-group">
<input type="text" name="name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="desc" placeholder="Description">
</div>
<div class="form-group">
<button class=btn-primary btn-block">Submit</button>
Go Back
</div>
</form>
<div class="row">
<% parents.forEach(function(module){%>
<ul class="list-group">
<li class="list-group-item" style="margin-bottom: 5%;">
<h2><%= module.name%></h2>
<%= module.description %>
<% console.log(module.children) %>
<%module.children.forEach(function(node){%>
<% console.log(node) %>
<%});%>
<div class="container">
<div class="row">
<div>
<form action="/<%= module._id %>" method="POST">
<div class="form-group">
<input type="text" name="name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="desc" placeholder="Description">
</div>
<button>Submit</button>
</form>
</div>
</div>
</div>
</li>
</ul>
</div>
<% }); %>
</div>
Can anyone tell where is the problem in above code or can anyone suggest any other way to make this type of parent-child structure????
It seems that parent.save() is asynchronus. Maybe you can try this instead.
parent.save().then(()=>{
console.log(parent.children);
res.redirect("/");
});
or you can use async-await after putting async before function definition,
await parent.save();
console.log(parent.children);
res.redirect("/");
Please do write in comment if problem still persists.

Categories