首页 > 解决方案 > 如何使用 nodejs 创建自引用 MongoDB 架构并发布路由?

问题描述

我正在尝试创建类似嵌套系统的父子系统,其中子系统与父系统具有相同的模式。下面是我的父模式,这里的子系统再次引用 parentSchema,

var mongoose    = require("mongoose");  
var parentSchema    =   new mongoose.Schema({
name: String,
children:[
    {
        ref: this
    }
  ],
});

module.exports  =   mongoose.model("Parent", parentSchema);

路线看起来像这样

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("/");
    }
 });
});

问题是当我将数据从表单发送到发布路由时,它会打印它,但在将其推送到 parent.children 然后打印 parent.children 后显示为空。问题出在哪里???EJS 页面如下所示:-

<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>

谁能告诉上面代码中的问题在哪里,或者任何人都可以提出任何其他方法来制作这种类型的父子结构????

标签: javascriptnode.jsmongodbexpressejs

解决方案


这似乎parent.save()是异步的。也许你可以试试这个。

parent.save().then(()=>{
  console.log(parent.children); 
  res.redirect("/");
});

async或者你可以在函数定义之前使用 async-await ,

await parent.save();
console.log(parent.children);
res.redirect("/");

如果问题仍然存在,请在评论中写下。


推荐阅读