所有我能想到這裏是你在呼喚它錯了。除了您的.populate()
參數看起來不正確之外,您不會在此顯示很多背景。
這是一個正確的房源爲重複的例子:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
var thingSchema = new Schema({
_id: Number,
name: String
},{ _id: false });
var parentSchema = new Schema({
name: String,
things: [{ type: Number, ref: 'Thing' }]
});
var Thing = mongoose.model('Thing', thingSchema),
Parent = mongoose.model('Parent', parentSchema);
mongoose.connect('mongodb://localhost/thingtest');
var things = { "one": 1, "two": 2, "three": 3 };
async.series(
[
function(callback) {
async.each([Thing,Parent],function(model,callback) {
model.remove({},callback);
},callback);
},
function(callback) {
var parentObj = new Parent({ "name": "me" });
async.each(
Object.keys(things).map(function(key) {
return { "name": key, "_id": things[key] }
}),
function(thing,callback) {
var mything = new Thing(thing);
parentObj.things.push(thing._id)
mything.save(callback)
},
function(err) {
if (err) callback(err);
parentObj.save(callback);
}
);
},
function(callback) {
console.log("filtered");
var options = {
path: 'things',
match: { "name": { "$in": ['two','three'] } }
};
Parent.find().populate(options).exec(function(err,docs) {
if (err) callback(err);
console.log(docs);
callback();
});
},
function(callback) {
console.log('unfiltered');
Parent.find().populate('things').exec(function(err,docs) {
if (err) callback(err);
console.log(docs);
callback();
})
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
);
這將始終如一地給出這樣的結果:
filtered
[ { _id: 55ec4c79f30f550939227dfb,
name: 'me',
__v: 0,
things:
[ { _id: 2, name: 'two', __v: 0 },
{ _id: 3, name: 'three', __v: 0 } ] } ]
unfiltered
[ { _id: 55ec4c79f30f550939227dfb,
name: 'me',
__v: 0,
things:
[ { _id: 1, name: 'one', __v: 0 },
{ _id: 2, name: 'two', __v: 0 },
{ _id: 3, name: 'three', __v: 0 } ] } ]
因此,需要在您的數據和通話好好看看。 .populate()
調用需要匹配「路徑」,然後還提供「匹配」以查詢要填充的文檔。
這不會有任何用處,其中「books」是一個ObjectId數組,用於引用的「Books」集合。這就是'.populate()'在這裏所暗示的用法。不是嵌入式文檔數組,而是這些文檔的ObjectId值。 –