Aye*_*azo 0 javascript mongoose mongodb
我有一个查询获取用户帖子,我希望只显示访问者选择的国家/地区的帖子.
到目前为止,我正在尝试做这样的事情:
var country = req.query.country || req.session.country || { $ne: '' };
Posts.find({})
.populate('_creator')
.where('_creator.country').equals(country)
.exec(function(err, posts) {
console.log(posts);
});
Run Code Online (Sandbox Code Playgroud)
不幸的是它不起作用.
我怎么能有类似这样的查询?
编辑:
这是Posts Schema:
var postsSchema = new mongoose.Schema({
_creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
text: { type: String, default: '' },
created_at: Date
});
Run Code Online (Sandbox Code Playgroud)
您不能在查询中包含填充字段,因为populate在初始查询完成后作为单独的查询执行.
有效执行此类查询的一种方法是首先查找所选国家/地区的用户的ID,然后查询这些用户的帖子.
// Get the _ids of the users of the selected country.
User.find({country: country}, {_id: 1}, function(err, users) {
// Map the user docs into an array of just the _ids
var ids = users.map(function(user) { return user._id; });
// Get the posts whose _creator is in that set of ids
Post.find({_creator: {$in: ids}}).populate('_creator').exec(function(err, posts) {
// posts contains your answer
});
});
Run Code Online (Sandbox Code Playgroud)