[英]How to create self referencing MongoDB schema and post routes using nodejs?
我正在嘗試創建類似嵌套系統的父子系統,其中子系統與父系統具有相同的模式。下面是我的父模式,這里的子系統再次引用 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 后顯示 null。 問題出在哪里??? 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>
誰能告訴上面代碼中的問題在哪里,或者任何人都可以提出任何其他方法來制作這種類型的父子結構????
似乎parent.save()
是異步的。 也許你可以試試這個。
parent.save().then(()=>{
console.log(parent.children);
res.redirect("/");
});
或者您可以在將async
放在 function 定義之前使用 async-await,
await parent.save();
console.log(parent.children);
res.redirect("/");
如果問題仍然存在,請在評論中寫下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.