您将如何访问已经找到的文档上的子文档?
假设我创建了以下模型:
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const barStructure = {
name: { type: String, require: true }
}
const fooStructure = {
name: { type: String, require: true },
bar: { type: schema.ObjectId, ref: 'bar', require: false }
}
var BarModel = mongoose.model('Bar', schema(barStructure));
var FooModel = mongoose.model('Foo', schema(fooStructure));
然后创建:
FooModel.create({ name: 'name', bar: new BarModel({ name: 'name' }) });
现在如何bar
从父母那里访问?
FooModel.findOne({ name: 'name' }, (err, result) => {
//How can I access bar here?
});
您可以使用猫鼬查询填充功能:
fooModel
.findOne({ name: 'name' })
.populate('bar')
.exec((err, foo) => {
if (err) return handleError(err);
console.log(foo.bar): // Access sub model
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句