我有我正在查询的名为“活动”的模型(使用猫鼬)。他们的架构如下所示:
var activitySchema = new mongoose.Schema({
actor: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
},
recipient: {
type: mongoose.Schema.ObjectId,
ref: 'User'
},
timestamp: {
type: Date,
default: Date.now
},
activity: {
type: String,
required: true
},
event: {
type: mongoose.Schema.ObjectId,
ref: 'Event'
},
comment: {
type: mongoose.Schema.ObjectId,
ref: 'Comment'
}
});
当我查询它们时,我正在填充actor
、recipient
、event
和comment
字段(所有引用)。之后,我还深度填充该event
字段以获得event.creator
. 这是我的查询代码:
var activityPopulateObj = [
{ path: 'event' },
{ path: 'event.creator' },
{ path: 'comment' },
{ path: 'actor' },
{ path: 'recipient' },
{ path: 'event.creator' }
],
eventPopulateObj = {
path: 'event.creator',
model: User
};
Activity.find({ $or: [{recipient: user._id}, {actor: {$in: user.subscriptions}}, {event: {$in: user.attending}}], actor: { $ne: user._id} })
.sort({ _id: -1 })
.populate(activityPopulateObj)
.exec(function(err, retrievedActivities) {
if(err || !retrievedActivities) {
deferred.reject(new Error("No events found."));
}
else {
User.populate(retrievedActivities, eventPopulateObj, function(err, data){
if(err) {
deferred.reject(err.message);
}
else {
deferred.resolve(retrievedActivities);
}
});
}
});
这已经是一个相对复杂的查询,但我还需要做更多。$or
如果它击中声明的部分{actor: {$in: user.subscriptions}}
,我还需要确保event
'privacy
字段等于字符串public
。我尝试使用$elemMatch
,但由于必须先填充事件,所以我无法查询它的任何字段。我也需要在多个其他查询中实现同样的目标。
我有什么办法可以像我描述的那样实现进一步的过滤吗?