简体   繁体   中英

How to update value inside an array from multiple array in Mongoose?

I have a User mongodb structure like below.

{
"_id" : ObjectId("54d2f68edbe2337d000e1568"),
"username" : "khayusaki@gmail.com",
"organization" : [ 
    {
        "idOrganization" : "54c8b01af927db992d021f58",
        "usertype" : 1,
        "displayname" : "K",
    },
    {
        "idOrganization" : "54c8b01af927db992d021f60",
        "usertype" : 2,
        "displayname" : "Khay",
    }
],
"__v" : 0
}

It means like a user can have many organizations, and each displayname and usertype depends on it. What I want to do is, I only want to update the displayname of one organization by using JSON from request body.

{
"Displayname" : "Khay Usaki",
"Email" : "khayusaki@gmail.com"
}

My mongoose query is like below.

User.findOne({username: req.body.Email},
            {organization: {$elemMatch: {idOrganization: '54c8b01af927db992d021f58'}}},     
                function(err, user) {
                    if (err) res.send(err);

                    user.organization[0].displayname = req.body.Displayname;
                    user.save();
                    res.json({'message' : 'User successfully updated'});
                }
});

If I add console.log(user) before save() function, it gives me what I want to.

{   
_id: 54d2f68edbe2337d000e1568,
organization: 
[ 
    { 
        idOrganization: '54c8b01af927db992d021f58',
        usertype: 1,
        displayname: 'Khay Usaki',
    } 
] 
}

But it really doesn't save.I wish there might be someone who could help me find a solution for it.

ps I tried with $push in User.findOne and it is also not working either.

=== Solution ===== Thanks @BatScream for the suggestion and it gets working as following.

User.findOneAndUpdate({
    username: req.body.Email,
    organization: {$elemMatch: {idOrganization: "54c8b01af927db992d021f58"}}
},
{$set: {"organization.$.displayname": req.body.Displayname}}, {},
function(err, response) {
    // handle own response
});

You could use the $ positional operator in the findOneAndUpdate method.

 Model.findOneAndUpdate({"username": req.body.Email,
         "organization.idOrganization":"54c8b01af927db992d021f58"},
         {$set:{"organization.$.displayname":req.body.Displayname}},
         {},
 function(err,resp){//handle response})

尝试

user.organization.add(another_orginaztion);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM