0

I have built an API that updates records in MongoDB using mongoose, but currently what happening is if I am passing only 4 field values in the JSON file of postman and try to update then all the values are updating with value null except that 4 fields which I had passed in JSON so can anyone help me how I can pass dynamic field and value that update only passed values of collection not all the fields of collection.

Passes JSON :

{
    "preferance_id" : "60fe9ba1766d10d65c64083c",
    "is_active": true,
    "price_blur":true,
    "affiliate_commission":27,
    "language_code": "en"
 }

Update call which I have passed in node js

transaction.update(PreferencesMasterName,
                    { _id: new mongoose.Types.ObjectId(preferance_id) }, {
                        subscriptin_vat : subscriptin_vat,
                        popular_normal : popular_normal,
                        popular_crawled : popular_crawled,
                        price_blur : price_blur,
                        blur_rule : blur_rule,
                        affiliate_commission : affiliate_commission,
                        red_lock : red_lock,
                        automatic_dummy_price : automatic_dummy_price,
                        ...
                        is_active: is_active
                })

I want to pass dynamic field and values here instead of this because due to this other values are set will null value. So, can anyone have an idea how to do this?

Parth Shah
  • 128
  • 1
  • 9

1 Answers1

2

You can do something like this:


const data = res.body; // should be an object that needs to updated

 transaction.update({_id: PreferanceMasterName._id}, data, {new: true }, ( error, obj ) => {
            if( error ) {
                console.error( JSON.stringify( error ) );
            }
            console.log( obj );
        });

In certain cases new doesn't work, you can use : { returnOriginal: false }; for more details, you can check this thread there are multiple ways you can do this.

Please check update how to use it.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35