This REST endpoint updates the favourites list in my database, by removing qname from user.favourites.
My problem is that although updatedUser.favourites is correct at the end of the code, this is not actually being persisted in the database (similar code to add a qname on a separate endpoint do work). I'm sure this is a silly mistake, but what I've written feels intuitively correct.
exports.remQname = function (req, res, next) {
var userId = req.user.id;
var qname = req.params.qname;
console.log('addQname %s %s', userId, qname);
User.findOne({
_id: userId
}, function(err, user) {
if (err) return next(err);
if (!user) return res.json(401);
console.log(user);
// if the qname already in list, remove it, otherwise add it
var favourites = user.favourites;
var matches = _.remove(favourites, function (f) {
return f == qname
});
console.log('Matches: %s %s', matches, favourites);
user.favourites = favourites;
user.save(function(err, updatedUser){
if (err) throw err;
console.log(updatedUser); // correct info, but does not reflect database content
res.status(200).send(updatedUser.favourites);
});
});
};
Here is my Schema
var UserSchema = new Schema({
email: String,
password: String,
token: String,
role: {type: String, default: 'user'},
favourites: Array
});
module.exports = mongoose.model('User', UserSchema);