I've been working on a simple update function, that looks as follows:
exports.update = function update(req, res, next){
User.findById(req.param('userId'))
.exec(function (err, user) {
if(err) return next(err);
if(!user)
return res.sendData(null, 404, lang.userNotFound);
var info = req.param('info');
// Get the update to be made, in JSON format
if(info !== Object(info)) info = JSON.parse(info);
user.info = setProperties(user.info, info);
// console.log(user) gives the updated user object
user.save(function(err, usr) {
if (err) return next(err);
// console.log(usr) shows the updated user object
res.sendData();
});
});
};
function setProperties(object, update) {
if(update!== Object(update))
object = update;
else {
for (var prop in update) {
if (object.hasOwnProperty(prop))
object[prop] = setProperties(object[prop], update[prop]);
else
object[prop] = update[prop];
}
}
return object;
}
But unfortunately, although everything seems to work, in my Database nothing changes. I do not get any errors. Could anyone shed some light on this mystery? Thanks!
For reference (if it is relevant), here is my Schema:
var UserSchema = new Schema({
createdAt: {type: Date, default: Date.now},
lastActivity: {type: Date, default: Date.now},
info : {type : Schema.Types.Mixed},
});
Ah, I found the problem. Mongo was indeed performing the save, but it didn't know that an attribute had changed.
In the end, fixing it was as simple as adding
user.markModified('info');
And then everything performs as expected. It's a shame that Mongoose does not recognize this for us. Thanks to @vinz243 for pointing me in the right direction!