猫鼬是什么意思? [英] what does populate in mongoose mean?

查看:72
本文介绍了猫鼬是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下我不明白的代码行,尽管有很多教程提供了与populate示例相关的信息,但是没有任何教程可以解释其确切含义.这里是一个示例

I came across the following line of code which I couldn't understand ,although there are lot of tutorials that gives information related to examples of populate but there is none that explains what exactly it means.Here is a example

var mongoose = require('mongoose'), Schema = mongoose.Schema

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

var StorySchema = new Schema({
  _creator : {
     type: Schema.ObjectId,
     ref: 'Person'
  },
  title    : String,
  fans     : [{ type: Schema.ObjectId, ref: 'Person' }]
});

var Story  = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
Story.findOne({ title: /Nintendo/i }).populate('_creator') .exec(function (err, story) {
if (err) ..
  console.log('The creator is %s', story._creator.name);
  // prints "The creator is Aaron"
})

猫鼬中的

推荐答案

populate()函数用于在引用内部填充数据.在您的示例中,StorySchema具有_creator字段,该字段将引用_id字段,该字段基本上是mongodb文档的ObjectId.

populate() function in mongoose is used for populating the data inside the reference. In your example StorySchema is having _creator field which will reference to the _id field which is basically the ObjectId of the mongodb document.

populate()函数可以接受字符串或对象作为输入.

populate() function can accept a string or an object as an input.

其中字符串是需要填充的字段名称.您的情况是_creator.猫鼬从mongodb中找到一个文档后,结果如下所示:

Where string is the field name which is required to be populated. In your case that is _creator. After mongoose found one doc from mongodb and the result of that is like below

_creator: {
  name: "SomeName",
  age: SomeNumber,
  stories: [Set Of ObjectIDs of documents in stories collection in mongodb]
},
title: "SomeTitle",
fans: [Set of ObjectIDs of documents in persons collection in mongodb]

填充也可以接受对象作为输入.

populate can also accept the object as an input.

您可以在这里找到猫鼬populate()函数的文档: http://mongoosejs.com/docs/2.7.x/docs/populate. html https://mongoosejs.com/docs/populate.html

You can find the documents of mongoose's populate() function here : http://mongoosejs.com/docs/2.7.x/docs/populate.html or https://mongoosejs.com/docs/populate.html

这篇关于猫鼬是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆