2017-02-07 197 views
0

如何訪問已找到的文檔上的子文檔?貓鼬子文檔訪問

比方說,我創建了以下型號:

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? 
}); 

回答

0

可以使用貓鼬Query Population功能:

fooModel 
    .findOne({ name: 'name' }) 
    .populate('bar') 
    .exec((err, foo) => { 
    if (err) return handleError(err); 
    console.log(foo.bar): // Access sub model 
    }); 
+0

這確實有效。謝謝 :) – Xeul