ref 是什么意思 猫鼬

iLi*_*LiA 3 mongoose node.js

我正在阅读 mongoosejs 文档,了解填充方法并使用“ref”填充有点难以理解,我也看到了很多 stackoverflow 问题,MDN,但没有人花太多时间来解释这一点

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);
Run Code Online (Sandbox Code Playgroud)

所以这是一个例子,文档说 ref: 引用我们应该使用哪个模型,但在这种情况下,作者有对 person 的引用,它的类型是 objectId 以及它如何存储整个模式(_id,名称,年龄,故事)与故事属性相同,它如何存储整个架构(以猫鼬语言“文档”表示)。

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"
});
Run Code Online (Sandbox Code Playgroud)

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

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

Akr*_*ion 5

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

stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
Run Code Online (Sandbox Code Playgroud)

Story 的对象ObjectId将仅存储在Person stories数组中,当您调用populate('stories')mongoose 时,它​​将执行另一个查询来查找并匹配所有对象ObjectId并返回实际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);
    });
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。