I have a User mongodb structure like below.
{
"_id" : ObjectId("54d2f68edbe2337d000e1568"),
"username" : "[email protected]",
"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" : "[email protected]"
}
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.
p.s. 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
});
elemMatchis not required."organization.idOrganization":"54c8b01af927db992d021f58"like you asked me to. It showed me *MongoError . So I had to try again with$eleMatchand it works.