gpt4 book ai didi

mongoose - 在 Mongoose 中填充是什么意思?

转载 作者:行者123 更新时间:2023-12-04 04:51:26 27 4
gpt4 key购买 nike

我遇到了以下我无法理解的代码行,尽管有很多教程提供了与 populate 的示例相关的信息。但没有一个能解释它究竟意味着什么。这是一个例子

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() mongoose 中的函数用于填充引用中的数据。在您的示例中 StorySchema_creator将引用 _id 的字段字段基本上是 ObjectId mongodb 文档。

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



其中 string 是需要填充的字段名称。在你的情况下是 _creator .在 mongoose 从 mongodb 中找到一个文档后,结果如下
_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.



你可以找到 Mongoose 的文档 populate()功能在这里:
http://mongoosejs.com/docs/2.7.x/docs/populate.htmlhttps://mongoosejs.com/docs/populate.html

关于mongoose - 在 Mongoose 中填充是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38051977/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com