首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的mongoose数组没有被填充,甚至没有值存储在其中?

为什么我的mongoose数组没有被填充,甚至没有值存储在其中?
EN

Stack Overflow用户
提问于 2019-05-21 04:33:43
回答 1查看 40关注 0票数 1

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中,它看起来像这样:

因此,您可以清楚地看到,数组中没有子论坛。

问题是什么?我如何解决它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-21 04:51:05

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56227819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档