Juicy
Juicy

Reputation: 12530

Mongoose doesn't update my fields

I'm trying to update an entries, if they are found in my Mongo DB:

exports.insert = function(project, data) {

    data.forEach(function(d){
        d.project = project;
        var asset = new Asset(d);

        Asset.findOne({
            project: asset.project,
            ip: asset.ip
        }, function(err, match) {
            if (err) { return next(err); }

            if (match) {
                console.log('asset found, updating');
                match.mac = 'blablah';
                match.save();
            }
        });
    });

};

I also tried to update like this:

asset.mac = 'blalah';
match.update(asset);

In both cases my fields don't update in the DB. I see no change.

There may be smarter ways to do this but I need to be able to use save or update to do it for future.

NB: Although findOneAndUpdate may be the preferred way of doing this, I'm really curious to know why save() or update() do not work in my case. I would like to know how to use those methods to update my document.

Upvotes: 1

Views: 694

Answers (1)

SlashmanX
SlashmanX

Reputation: 2611

If you're trying to find one entry and update it, you should use findOneAndUpdate:

Asset.findOneAndUpdate({
    project: asset.project,
    ip: asset.ip
}, {
    mac: 'blablah'
}, function (err, docThatWasUpdated) {
    ....
})

Upvotes: 2

Related Questions