Cherif
Cherif

Reputation: 5383

Mongodb : array element projection with findOneAndUpdate doesn't work?

I am using Mongoose and I'm trying to update an array element and get it back updated. This is my document structure :

{   name:String,
    friends:[
        {   name:String,
            age:Number
        }
    ]
}

When I execute the following query I get all the friends in the result but I only want to get 25 year old friends back :

theCollection.findOneAndUpdate(
    {   name : 'cherif',
        'friends.name':'kevin'
    },
    {   $set:{
            'friends.$.age':25
        }
    },
    {   friends:
        {   $elemMatch:
            {   age : 25 } 
        }
    },
    function(err,result){
        if (!err) {
            console.log(result);
        }});

Upvotes: 2

Views: 9265

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311895

As the docs for findOneAndUpdate specify, you need to include your projection object as the select property of the options parameter:

theCollection.findOneAndUpdate(
    {   name : 'cherif',
        'friends.name':'kevin'
    },
    {   $set:{
            'friends.$.age':25
        }
    },
    {   select: { 
            friends: {
               $elemMatch: 
               {   age : 25 } 
            }
        }
    },
    function(err,result){
        if (!err) {
            console.log(result);
        }
    });

Upvotes: 11

Related Questions