Simon H
Simon H

Reputation: 21005

Mongoose not saving to database

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);

Upvotes: 0

Views: 186

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311865

You can directly remove all instances of a specific value from an array field using $pull, so it would be more efficient to let MongoDB do the work rather than trying to manipulate the array yourself.

User.update({_id: userId},
            {$pull: {favourites: qname}},
            function(err, numberAffected, raw) { ... });

I'd also suggest changing your definition of favourites in the schema to be [String] instead of just Array if it does contain an array of strings.

Upvotes: 2

Simon H
Simon H

Reputation: 21005

It had something to do with lodash - this works instead

    var newFavs = _.reject(user.favourites, function (f) {
        return f == qname
    });

    console.log('Favourites - Old: %s New: %s', user.favourites, newFavs);

    // delete user.favourites;
    user.favourites = newFavs;

Upvotes: 1

Related Questions