Node.js 在聚合期间,mongoose/mongodb是否可以访问模式中的对象引用?
我正在处理一个查询,该查询从我的mongo数据库中的两个不同的obj引用中读取。我将用一个简单的例子来说明我在寻找什么 我有3个模式:Node.js 在聚合期间,mongoose/mongodb是否可以访问模式中的对象引用?,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我正在处理一个查询,该查询从我的mongo数据库中的两个不同的obj引用中读取。我将用一个简单的例子来说明我在寻找什么 我有3个模式: User = new Schema({ places:[{type: Schema.Types.ObjectId, ref:'Place'}], shouts:[{type: Schema.Types.ObjectId, ref:'Shout'}] }); Place = new Schema({ name:String, des
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);
});
}
这通常很好,但是一旦调用$match操作符,我就会得到一个空数组,我猜这与返回未定义子对象的对象引用有关。这方面有什么工作吗?或者这是否意味着我必须采取另一种方式来利用人口
感谢所有预先提供的帮助在聚合过程中无法访问对象引用的数据,我在项目中采用的解决方法是在相关模式中添加对所有者的引用
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);
});
});
}
这正是我找到的解决我特殊需要的方法,我希望它能帮助别人。你可能想阅读-。您需要解析客户端中的引用。Mongoose使用
populate
功能为您实现这一点。聚合
代码是在服务器端执行的,因此引用不会自动解析。感谢回复@BatScream,这只是一个理解错误根源的示例,我正在使用geospacial索引,因此在客户端解决这一问题可能比需要的困难。假设,如果子模式将引用parrent,您是否认为可以聚合子模式,填充父模式,然后在将结果发送到客户端之前进行筛选?或者这会是一个糟糕的性能瓶颈吗?