Friday 15 April 2011

node.js - Returning only first element of a sub array with $elemMatch -



node.js - Returning only first element of a sub array with $elemMatch -

i'm using node , mongoose, , have schema looks 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 } }); // grouping schema var groupschema = new schema({ 'groupowner': [{ type: mongoose.schema.types.objectid, ref: 'user' }], 'groupname': string, 'subscribers': [subscriberschema], });

i query grouping find groups user (stored in req.user._id via token authentication) subscriber (i.e. _id in subscribers array), , homecoming single subscribers array element _id.

i've read mongo documentation on $elemmatch seems need, , built query below. returns info want, returns elements of subscribers array. how can homecoming single element of subscribers array matches req.user._id?

current query, returns elements of subscribers:

grouping .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 retrieve groups user: ' + err.message); res.status(500) } else { res.json(data); } });

this returns next 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 $elemmatch docs, assume see user 1234 since that's record matches req.user._id. doing wrong here?

thanks!

in projection parameter, utilize dollar operator:

{"user.$": 1}

this homecoming grouping single object in 'subscribers' array.

node.js mongodb mongoose

No comments:

Post a Comment