The problem
我知道Stack上有很多关于这个问题的类似问题,但我无法通过这些帖子来解决它。
我正在创建一个简单的论坛应用程序。我有2条创建论坛和子论坛的路线。一个论坛可以有多个子论坛。一个子论坛分配给一个论坛。
我的论坛架构如下所示:
const mongoose = require("mongoose");
const forumSchema = new mongoose.Schema({
title: String,
subTitle: String,
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post" }],
subForums: [{ type: mongoose.Schema.Types.ObjectId, ref: "Subforum" }]
});
const Forum = mongoose.model("Forum", forumSchema);
module.exports = Forum;
对子论坛的模式进行:
const mongoose = require("mongoose");
const subForumSchema = new mongoose.Schema({
title: String,
subTitle: String,
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post" }],
forum: { type: mongoose.Schema.Types.ObjectId, ref: "Forum" }
});
const SubForum = mongoose.model("Subforum", subForumSchema);
module.exports = SubForum;
如果我创建了一个新论坛并将其保存,我会将其保存在数据库中。当然,现在还没有子论坛。然后,我创建一个子论坛,如下所示(我使用 req.body.forum
**):**提供刚刚创建的论坛的id
router.post("/newSub", verify, async (req, res) => {
// TODO: Only admin can do this
const subForum = new SubForum({
title: req.body.title,
subTitle: req.body.subTitle,
forum: req.body.forum
});
try {
await subForum.save();
res.send(subForum);
} catch (err) {
res.status(400).send(err);
}
});
我得到的响应是它已经被创建了。新的子论坛如下所示:
但是,当我搜索所有论坛,并想用它的子论坛填充它时,它不会起作用。在Robomongo中,它看起来像这样:
因此,您可以清楚地看到,数组中没有子论坛。
问题是什么?我如何解决它?
发布于 2019-05-21 04:51:05
在您的代码中,我看不到您实际上将subforum
id推入forum.subforum
数组的任何地方。在创建并保存subforum
之后,还必须将该subforum id
推入forum.subforums
数组并保存。
https://stackoverflow.com/questions/56227819
复制相似问题