在聚合过程中,mongoose / mongodb是否可以访问模式中的对象引用?

我正在处理从mongo数据库中的2个不同的obj参考中读取的查询。 我将使用一个简单的例子,即时通讯寻找。

我有3个模式:

User = new Schema({ places:[{type: Schema.Types.ObjectId, ref:'Place'}], shouts:[{type: Schema.Types.ObjectId, ref:'Shout'}] }); Place = new Schema({ name:String, description:String, }); Shout = new Schema({ content:String, }); 

我最大的问题是如果mongoose或mongodb在执行聚合方法时有权访问objectId引用。 请允许我详细说明。

 module.exports.askForShoutInPlace = function(req, res){ var pname = new RegExp(req.params.pname, 'i'); User.aggregate( [ {'$match':{ 'places':{ '$elemMatch':{'name':pname} } }, {'$project':{ shout:'$shouts'} }, {'$unwind':'$shouts'}, {'$group':{_id:'$shouts'}} ]).exec(function(err, results){ res.send(results); }); } 

这通常工作正常,但是一旦$匹配运算符被调用,我得到一个空数组,即时猜测它必须做对象引用返回未定义的子对象。 有没有解决这个问题? 还是这意味着我不得不采取另一条路线来使用填充?

感谢所有的帮助提前

在聚合stream程期间无法访问对象引用数据,我在项目中使用的工作是在相关模式中添加对所有者的引用。

 User = new Schema({ places:[{type: Schema.Types.ObjectId, ref:'Place'}], shouts:[{type: Schema.Types.ObjectId, ref:'Shout'}] }); Place = new Schema({ owner:{type: Schema.Types.ObjectId, ref:'Place'}, name:String, description:String, }); Shout = new Schema({ owner:{type: Schema.Types.ObjectId, ref:'Place'}, content:String, }); 

然后用于直接在子文档上进行聚合,以获得拥有该地点实例的唯一用户,这样我就可以获得匹配查询和地点的留言结果。

例:

 module.exports.askForShoutInPlace = function(req, res){ var pname = new RegExp(req.params.pname, 'i'); var stringQ = new RegExp(req.paramos.qcontent, 'i'); Place.aggregate( [ //find Places that match criteria {'$match':{'name':pname}}, //select owner id object to result {'$project':{ owner:'$owner'}}, //group those results to single array with unique ids of users {'$group':{_id:'$owner'}} ]).exec(function(err, results){ //find user shouts that match string and belong to owners know to be owners of a place Shout.find({'content':stringQ}).where({'owner':{'$in':results}}).exec(function(err, shouts){ res.send(shouts); }); }); } 

这只是我发现解决我的特殊需求的方式,我希望这可以帮助别人。