Aral Roca
Aral Roca

Reputation: 5919

Mongoose: Part of array

I have this MongoDB Notification Model:

Using Mongoose in NodeJS I create a query that return all the documents where my user is inside the Subscriptions array.

 Notification
    .find({subscriptions:{$elemMatch: {user: req.user}}})  
    .sort('-created')
    .exec(function (err, notifications) {

        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {

            res.jsonp(notifications);
        }
    });

This query works, and returns the documents that I wanted... But I don't want exactly this... This code returns, in the documents returned, all subscriptions array, including other users. If there are 10.000 users inside the subscriptions array, all the users are returned in all documents.

How can I extract a part of the array? I want that only my user is returned inside the subscriptions array. Why? for security and performance reasons.

I tried this query:

    .find({subscriptions:{$elemMatch: {user: req.user}}}, {'subscriptions.$': 1})

This query only returns one user in the subscriptions array (my user). But... Is not returned any field more except the subscriptions array...

Any suggestion?

Upvotes: 0

Views: 64

Answers (1)

Sede
Sede

Reputation: 61225

You can include other fields in your result like this:

.find({ 'subscriptions': { '$elemMatch': { 'user': req.user }}}, 
    { 'subscriptions.$': 1, 'content': 1, 'created': 1, 'user': 1 }
)

Upvotes: 1

Related Questions