具有一对多关系的 Mongoose 文档引用

新手上路,请多包涵

我正在为一个新项目设计数据库结构,而且我对 MongoDB 很陌生,显然是 Mongoose。

我已经阅读了 Mongooses 人口 文档,其中它具有一对多的关系,一个 Person 文档到许多 Story 文档,但让我感到困惑的部分是 Story 文件引用了 Person 它所属的文件, Person 模式已经设置好了,所以它有一个数组,包含 Story 文件c02a它“拥有”。

我正在设置与此非常相似的东西。但我一直认为,在创建新的 Story 文档以拥有 Person 文档 ID 时会更容易。但也许那只是因为我更熟悉使用连接的 MySQL 关系。

如果这是最好的方法(我确信它是,因为它在文档中),当新的 Story 文档被创建时,什么是更新故事数组的最佳方法相关 People 它属于什么文件?我查看但找不到任何更新现有文档以添加对其他文档的引用(或为此删除它们)的示例

我确信这是一个我刚刚忽略的简单解决方案,但任何帮助都会很棒。谢谢!

原文由 Justin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 506
1 个回答

这是创建一对多关系的好方法。

  1. 首先,我们在 Comment.js 中定义 Comment 模型。
 const mongoose = require("mongoose");

const Comment = mongoose.model(
  "Comment",
  new mongoose.Schema({
    username: String,
    text: String,
    createdAt: Date
  })
);

module.exports = Comment;

  1. 在 Tutorial.js 中,添加如下评论数组:


const mongoose = require("mongoose");

const Tutorial = mongoose.model(
  "Tutorial",
  new mongoose.Schema({
    title: String,
    author: String,
    images: [],
    comments: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Comment"
      }
    ]
  })
);

module.exports = Tutorial;

  1. 在 server.js 中,添加 createComment 函数。

const createComment = function(tutorialId, comment) {
  return db.Comment.create(comment).then(docComment => {
    console.log("\n>> Created Comment:\n", docComment);

    return db.Tutorial.findByIdAndUpdate(
      tutorialId,
      { $push: { comments: docComment._id } },
      { new: true, useFindAndModify: false }
    );
  });
};

原文由 MD SHAYON 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题