【问题标题】:what does ref means mongooose红色是什么意思
【发布时间】:2019-05-12 18:11:19
【问题描述】:

我正在阅读 mongoosejs 文档并使用填充方法并使用“ref”填充有点难以理解

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);

所以这是一个例子,文档说 ref: 引用我们应该使用哪个模型,但在这种情况下,作者对 person 有 ref,它的类型是 objectId,它如何存储整个模式(_id、name、age ,stories) 和 stories 属性相同,它如何存储整个模式(在猫鼬语言“文档”中)。

Story.
findOne({ title: 'Casino Royale' }).
populate('author').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
// prints "The author is Ian Fleming"
});

在这里,当我分析此代码时,会在故事模型中找到标题字段,然后它也会在故事模型中获取作者属性,然后从第二个模式中获取名称。如代码所示,作者引用了 person 模型,但我承认它的类型是 objectId,它如何存储整个模式(_id、name、age、stories)

如果有人可以解释这一点 更多细节,他们将帮助许多像我一样没有得到它的人

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    ref 基本上意味着mongoose 将存储ObjectId 值,当您调用populate 时,使用这些ObjectIds 将为您获取并填充文档。所以在这种情况下:

    stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
    

    Story 的 ObjectId 只会存储在 Person stories 数组中,当您调用 populate('stories') 时,猫鼬会进行另一个查询以查找并匹配所有 @ 987654329@ 并返回实际的 Stories 对象。

    所以ref 只是告诉 mongoose 你想在其中存储对另一个模型的引用,并且在某些时候你想populate 那些并通过该引用获得完整的模型。

    从某种意义上说,它只不过是另一个集合的 foreign 键,当调用 populate 时,您可以通过它获取实际文档。

    下面是分解代码:

    Story.findOne({ title: 'Casino Royale' })  // <-- filter on title
      // once a story is found populate its `author` with full author document 
      // instead of the `ObjectId` stored by the `ref`
      .populate('author')
      // execute the current pipeline
      .exec(function (err, story) { // handle the resulting record
        if (err) return handleError(err);
          console.log('The author is %s', story.author.name);
        });
    

    希望这会有所帮助。

    【讨论】:

    • “故事的 ObjectId 将仅存储在 Person 故事数组中”是什么告诉猫鼬存储该 Story 的 objectid 尤其是在 stories 属性中,并且在 storySchema 中定义了 2 个不同的 id? ,对不起,我认为这是猫鼬中最晦涩的东西
    • 在关系数据库中,您有一个外键概念。那是完全一样的。您存储一个外键 (ObjectId),以便在您执行 populate 时可以“关联”到另一个表/文档集合
    • 所以你的意思是故事,作者和粉丝因为 ref 而拥有相同的 ID?
    • person 有故事 Id 的集合,story 有人物 Id 的集合,fan 也有人物 Id 的集合。如果一个人既是故事的作者又是故事的粉丝,那么这些 id 很可能是相同的。
    • 因此,如果我们首先对我发布的最后一个代码(Story.findone())求和,它会在 Story 模型中找到带有标题的字段,然后填充作者,这意味着它会在 Story 模型中获取作者属性,并且然后它查询作者姓名,但它如何与 Story 建立联系,因为 personSchema 中的 _id 属性和 storySchema 中的 author 属性具有相同的值?如果您感到困扰,请不要随心所欲地回答,或者如果您愿意,可以开始聊天
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2023-02-24
    • 2011-08-04
    • 1970-01-01
    相关资源
    最近更新 更多