当使用具有嵌套字段的mongoose模型时,可能需要将嵌套字段中的引用字段填充(filling)。
Mongoose中的populate函数使我们能够轻松地处理这种情况,使得查询结果中包含嵌套引用字段的详细信息。
下面我们将详细介绍如何使用populate函数处理嵌套字段。步骤如下:
1. 创建模型
首先,我们创建两个模型Parent和Child:
const mongoose = require('mongoose');
const childSchema = new mongoose.Schema({
name: String,
});
const parentSchema = new mongoose.Schema({
name: String,
children: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Child' }],
});
const Child = mongoose.model('Child', childSchema);
const Parent = mongoose.model('Parent', parentSchema);
module.exports = { Child, Parent };
在上面的模型中,Parent模型具有一个嵌套字段children,其类型为mongoose.Schema.ObjectID,并引用了Child模型。
2. 创建数据
接下来,我们创建测试数据。首先创建一个Child实例:
const child = new Child({
name: 'John Doe'
});
然后创建一个Parent实例,并将child实例添加到其嵌套字段children中:
const parent = new Parent({
name: 'Mary Smith',
children: [child._id]
});
3. 填充数据
现在,我们将使用Mongoose的populate函数填充parent模型中的children数组。这将返回一个包含完全填充引用字段的parent对象。
Parent
.findOne({ name: 'Mary Smith' })
.populate('children')
.exec(function (err, parent) {
if (err) return handleError(err);
console.log('The parent is:', parent);
});
输出结果:
{
"_id": "5fb78b7f8943c10e8386889a",
"name": "Mary Smith",
"__v": 0,
"children": [
{
"_id": "5fb78b7f8943c10e83868899",
"name": "John Doe",
"__v": 0
}
]
}
4. 嵌套填充
如果我们的Child模型或其嵌套字段中还有引用字段,则可以使用populate函数来填充这些引用字段。例如:
const grandChildSchema = new mongoose.Schema({
name: String,
});
const childSchema = new mongoose.Schema({
name: String,
grandchildren: [{ type: mongoose.Schema.Types.ObjectId, ref: 'GrandChild' }],
});
const GrandChild = mongoose.model('GrandChild', grandChildSchema);
const Child = mongoose.model('Child', childSchema);
// create a grandchild instance
const grandchild = new GrandChild({
name: 'Jane Doe'
});
// create a child instance with the grandchild as a reference
const child = new Child({
name: 'John Doe',
grandchildren: [grandchild._id]
});
// create a parent instance with the child as a reference, and fill the grandchildren field
const parent = new Parent({
name: 'Mary Smith',
children: [child._id]
}).populate({
path: 'children',
populate: {
path: 'grandchildren',
model: 'GrandChild'
}
}).exec(function (err, parent) {
if (err) return handleError(err);
console.log('The parent is:', parent);
});
输出结果:
{
"_id": "5fb78b7f8943c10e8386889a",
"name": "Mary Smith",
"__v": 0,
"children": [
{
"_id": "5fb78b7f8943c10e83868899",
"name": "John Doe",
"__v": 0,
"grandchildren": [
{
"_id": "5fb78c1e8943c10e8386889b",
"name": "Jane Doe",
"__v": 0
}
]
}
]
}
以上就是利用populate函数在mongoose中处理嵌套字段的完整攻略,包括创建模型、创建数据、填充数据和嵌套填充数据等过程。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:mongoose中利用populate处理嵌套的方法 - Python技术站