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
});
2 Answers 2
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})
1 Comment
Try
user.organization.add(another_orginaztion);
1 Comment
displayname inside related organization. Don't want to add another array with the same idOrganization with different displayname. And also it is showing there has no method 'add'.Explore related questions
See similar questions with these tags.
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.