javascript - 如何使用 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>
谁能告诉上面代码中的问题在哪里,或者任何人都可以提出任何其他方法来制作这种类型的父子结构????
解决方案
这似乎parent.save()
是异步的。也许你可以试试这个。
parent.save().then(()=>{
console.log(parent.children);
res.redirect("/");
});
async
或者你可以在函数定义之前使用 async-await ,
await parent.save();
console.log(parent.children);
res.redirect("/");
如果问题仍然存在,请在评论中写下。
推荐阅读
- kubernetes - Gitlab协调员在跑步者完成工作后等待5分钟 - 如何诊断
- c# - ASP.NET MVC 如何使用 ApplicationUser 和其他域类之间的多对多关系
- python - 转换为 int 的正确方法
- javascript - 单选按钮的 OnCheckedChanged 事件未在网格内触发,即使在设置自动回发后也是如此
- python - 有什么方法可以通过单击开始按钮来恢复运行?
- c++ - 您可以在不强制转换的情况下将位运算符与枚举类一起使用吗?
- json - 我正在尝试编写一个 bash 脚本来更新 package.json 依赖版本
- android-studio - 错误:参数格式不正确 - 在 android studio 中颤动
- python - 如何计算 Python 中所有可能的赋值排列?
- php - 刷新页面时如何保存以前的骰子?