【问题标题】:Mongoose Model ObjectId References Not WorkingMongoose 模型 ObjectId 引用不起作用
【发布时间】:2018-11-06 09:27:24
【问题描述】:

我正在使用 Mongoose 模型和参考资料。我一直在使用来自 mongoose 网站的代码,其中讨论了填充方法和引用。我试图让它在两个模型中保存各自的“引用”ID。它只是在故事模型中保存参考 ID。代码如下:

更新:在顶部添加了架构以提供帮助:

    var personSchema = Schema({
      _id: Schema.Types.ObjectId,
      name: String,
      age: Number,
      stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
    });

    var storySchema = Schema({
      author: { type: Schema.Types.ObjectId, ref: 'Person' },
      title: String,
      fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
    });

    var Story = mongoose.model('Story', storySchema);
    var Person = mongoose.model('Person', personSchema);

(模式结束)

var author = new Person({
  _id: new mongoose.Types.ObjectId(),
  name: 'Ian Fleming',
  age: 50
});

author.save(function (err) {
  if (err) return handleError(err);

  var story1 = new Story({
    title: 'Casino Royale',
    author: author._id    // assign the _id from the person
  });

  story1.save(function (err) {
    if (err) return handleError(err);
    // thats it!
  });
});

当你运行这段代码时,它会在 mongo 中生成:

  db.people.find()
  { "_id" : ObjectId("5be0a37f1dd61a343115e2c8"), "stories" : [ ], "name" : "Ian Fleming", "age" : 50, "__v" : 0 }
  db.stories.find()
  { "_id" : ObjectId("5be0a37f1dd61a343115e2c9"), "title" : "Casino Royale", "author" : ObjectId("5be0a37f1dd61a343115e2c8"), "__v" : 0 }

它似乎没有在“故事”中的人员集合中存储任何 ID。您不想将故事 ID 也保存在人员集合中吗?

我尝试修改代码以使其正常工作(移动了作者保存功能,直到设置故事 ID 之后):

 var author = new Person({
  _id: new mongoose.Types.ObjectId(),
  name: 'Ian Fleming',
  age: 50
 });

  var story1 = new Story({
    _id: new mongoose.Types.ObjectId(),
    title: 'Casino Royale',
    author: author._id    // assign the _id from the person
  });

  author.stories = story1._id;

  author.save(function (err) {
  if (err) return handleError(err);

  story1.save(function (err) {
    if (err) return handleError(err);
    // thats it!
  });

这给了我一个未定义的作者。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    Mongo 不会因为您添加了 Story 对象而自动添加到 Person“故事”字段。

    无论如何,您实际上并不需要将故事 ID 存储在 Person 对象中,因为您始终可以通过

    获得作者的故事列表
    db.stories.find({author: <id>})
    

    在这两个地方存储会产生冗余信息,如果不匹配,您必须选择一个作为事实。我认为最好不要重复。

    更新:

    引用似乎可以帮助您自动填充查询中的引用字段。根据this post,您可以像这样检索作者及其故事:

    db.persons.find({_id: <id>}).populate('stories')
    

    没有亲自使用过,但看起来很方便。

    用于填充的 Mongoose 文档:https://mongoosejs.com/docs/populate.html

    【讨论】:

    • 这是有道理的......他们确实在 Person 模式中包含了“stories”属性。我想知道在这种特殊情况下,这是否仅供参考(没有双关语)并且实际上并不需要。我会将他们的架构添加到问题中。
    • 也许这里解释了“他们”在做什么:stackoverflow.com/questions/18001478/…
    猜你喜欢
    • 2017-08-11
    • 2016-06-07
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2014-03-18
    • 2014-09-11
    相关资源
    最近更新 更多