Yogesh
Yogesh

Reputation: 3482

findOneAndUpdate with condition

I am trying to update a record based on condition:

Product.findOneAndUpdate({
        number: fields.number[0]
    }, {
        category: fields.category[0],
        name: fields.name[0]
    },
    function(err, product) {


    });

So, I want to check if fields.category is present then update else do not update the original value.

fields.category ? fields.category[0] : ""

What is the proper way to do it?

Upvotes: 0

Views: 2279

Answers (1)

Yogesh
Yogesh

Reputation: 3482

After little search, found that I need to use findOne method and update based on property

Product.findOne({number: fields.number[0]}, function (err, product) {
    product.category = fields.category ? fields.category[0] : product.category;
    product.name = fields.name[0];

    product.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

Upvotes: 3

Related Questions