Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple fields in a document with MongooseJS

Tags:

mongoose

Let's say I have an ABC schema that looks like this:

ABC = mongoose.Schema ({
    name: String
    , x: String
    , y: String
    , z: String
});

I want to update fields x and y if the name matched. Is that possible with the MongooseJS 'update' API?

I tried the following and didn't work:

ABC = mongoose.createConnection(uri).model('ABC', ABC)
...
ABC.findOne({'name': abc.name}).exec(function(err, found) {
    if(found) {
        ABC.update({'name':abc.name}, {'x':abc.x, 'y':abc.y}).exec();
    }
    ...
});

Even if this is possible, is it better to just update the ABC object and use ABC.save(abc) instead? I read in another thread that update is better than save because it's saver. Is that true?

Any advice is appreciated!

like image 429
Yi Z Avatar asked Feb 02 '26 14:02

Yi Z


1 Answers

Yes you can update multiple fields, you just need to do something like this

ABC.update({ name: 'whatever' }, {
    x: 'value1',
    y: 'value2'
},
function(err, data) {
    if (err) {
    } else if (!data){
    } else {
        return res.send(200, data);
    }
});
like image 157
alexiscrack3 Avatar answered Feb 05 '26 09:02

alexiscrack3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!