问题
I'm working on a query that reads from 2 different obj referentes inside my mongo database. I will use a simple example of what im looking for.
I have 3 schemas:
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,
});
My biggest question is if mongoose or mongodb has access to objectId references when executing the aggregate method. Allow me to elaborate.
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);
});
}
That usually works fine, however I'm getting an empty array once the $match operator is called, im guessing it has to do with the object references returning undefined subobjects. is there any work around this? or does this mean I have to take another route to employ populating?
thanks for all the help in advance
回答1:
there's no way to access object Referenced data during the aggregate Process, the work around I employed for my project was to add a reference to the owner in the schemas in question.
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,
});
And then employed to Aggregate directly on the subdocument to obtain the unique users who own the instances of of place, this way I can obtain a shout result matching a query and a place.
Example:
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);
});
});
}
this is just the way I found to work around my particular needs, I hope it might help somebody.
来源:https://stackoverflow.com/questions/34235382/does-mongoose-mongodb-have-access-to-object-references-in-schema-during-aggreg