gpt4 book ai didi

javascript - 为什么我的 Mongoose 数组没有被填充,甚至没有存储值?

转载 作者:行者123 更新时间:2023-11-30 19:33:06 25 4
gpt4 key购买 nike

问题

我知道 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);
}
});

我收到回复说它已创建。新的子论坛如下所示:

enter image description here

但是当我搜索所有论坛并想用它的子论坛填充它时,它不会工作。在 Robomongo 中它看起来像这样:

enter image description here

所以你可以清楚地看到数组中没有子论坛。

问题是什么,我该如何解决?

最佳答案

我在您的代码中没有看到您实际将 subforum id 推送到 forum.subforum 数组的任何地方。在您创建并保存 subforum 之后,您还必须将该 subforum id 推送到 forum.subforums 数组中并保存它。

关于javascript - 为什么我的 Mongoose 数组没有被填充,甚至没有存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com