简体   繁体   中英

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>
    <a href="/">Go Back</a>
  </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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM