I'm using node and mongoose, and have a schema that looks like this:
var SubscriberSchema = new Schema({
'user': [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
'level': { type: String, enum: [ 'owner', 'sub', 'commenter', 'poster' ] }
'dateAdded': { type: Date, default: Date.now }
});
// Group Schema
var GroupSchema = new Schema({
'groupOwner': [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
'groupName': String,
'subscribers': [SubscriberSchema],
});
I would like to query the group to find all groups where a user (stored in req.user._id
via token authentication) is a subscriber (i.e. their _id
is in the subscribers
array), and only return the single subscribers array element with their _id
.
I've read the Mongo documentation on $elemMatch as this seems to be what I need, and built the query below. This returns the information I want, but returns all elements of the subscribers
array. How can I return only the single element of the subscribers
array that matches my req.user._id
?
Current query, returns all elements of subscribers
:
Group
.find( { "subscribers.user": req.user._id}, { subscribers: { $elemMatch: { user: req.user._id }}} )
.sort('groupName')
.populate('groupOwner', 'email firstName lastName')
.populate('subscribers.user', 'email firstName lastName')
.exec(function(err, data) {
if (err) {
logger.error('Unable to retrieve groups for user: ' + err.message);
res.status(500)
} else {
res.json(data);
}
});
This returns the following for subscribers (via util.inspect(data[0].subscribers)
):
Subscribers
[{
user:
[ { _id: 1234,
email: 'me@here.com',
firstName: 'Testy',
lastName: 'Testelson' } ] }
user:
[ { _id: 5678,
email: 'you@there.com',
firstName: 'Biggy',
lastName: 'Smalls' } ] }]
Based on the $elemMatch docs, I would assume I would only see user 1234 since that's the record that matches req.user._id
. What am I doing wrong here?
Thanks!