我正在尝试在填充方法中使用查询条件。 如果使用条件,则仍会填充所有记录,但不满足条件的记录会将填充字段设置为空, 例如:
var query = BookModel.find();
query.populate('author','name',{name:'author1'});
query.find(function(err,books){
console.log(books);
});
Then the output is:
[ { author: { _id: 4ea0db52e09aa6aad2e831fe, name: 'author1' },
title: 'book1',
_id: 4ea0dbebc191848704000005 },
{ author: null,
title: 'book2',
_id: 4ea0dbebc191848704000006 } ,
{ author: null,
title: 'book3',
_id: 4ea0dbebc191848704000007 } ,
{ author: null,
title: 'book4',
_id: 4ea0dbebc191848704000008 } ]
但是,我希望输出结果中只有第一条记录。我该如何解决这个问题?
最佳答案
我遇到了与您面临的相同问题,我尝试了上面的代码,但它并没有帮助我解决问题。我找到了一种方法,就像你想要的那样。您不能使用 populate 进行这种过滤,您必须使用 mongodb 的原始查询来过滤数据。
// db['result'] is the name of database
db['result'].aggregate([
// this is just like populate this populate the user field
{
$lookup:{
from:'users',
localField:'user',
foreignField:'_id',
as:'user'
}
},
// unwind convert the array to objects to apply filter on it
{
$unwind:{
preserveNullAndEmptyArrays : true, // this remove the object which is null
path : "$user"
}
},
// in match you have to define your condition this check if the user has role equals to 3
{
$match:{
"user.role": 3
}
},
{
// this provide pagination
$facet: {
edges: [
{ $skip: sk },
{ $limit: lm },
],
/* pageInfo: [
{ $group: { _id: null, count: { $sum: 1 } } },
],*/
},
}
], function (err, result) {
if (err) {
// this res is send if there is some error
console.log(err);
callback(500, err)
} else {
// you get the data
console.log(result);
callback(200, result)
}
});
关于javascript - Node Mongoose 填充条件不返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196620/