I'm trying to update a object inside another but when the object is updated replace all information.
Structure
var userSchema = mongoose.Schema({
local : {
email : {type: String, unique: true},
password : String
}
name: String
});
before be updated
user
{
name = 'foo',
local {
email: "foo@foo.com",
password: "foopass"
}
}
after be updated
{
name = 'foo',
local {
email: "foo@foo.com"
}
}
this is my query:
router.put('/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: { name: req.body.name, local: {email: req.body.email} }
}, { upsert: true },
function(err, obj) {
return res.json(true);
});
});
Use dot notation in the $set key to target just the email property of local instead of updating the whole local object:
router.put('/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: { name: req.body.name, 'local.email': req.body.email }
}, { upsert: true },
function(err, obj) {
return res.json(true);
});
});