made_in_india
made_in_india

Reputation: 2279

Insert default values not working mongodb

I am using mongoose version 5.2.5 and here is the sample model of my order

....
let PlaceOrderSchema = new mongoose.Schema({
        any: {}
}, { strict: false },
    { timestamps: { updatedAt: 'last_updated', createdAt: 'created' });

I am using the above model in main script with mongoose save and findOneAndUpdate. In our production system , we are seeing many document that does not have last_updated key missing in the save document.

Here are sample code of the mongoose save method and findOneAndUpdate in our main script.We are seeing some of the documents have updated_at keys while very few of them does not have it while saving the document

let orderModel = require('./orderModel');
let newOrder = {
    order_no: 1234
};

//save usage code
(new Order(newOrder).save({lean: true}, ()=> {

  //do...something

}));

//findOneAndUpdate usage Code
 let orderNo = 123
 OrderModel.findOneAndUpdate({ order_no: orderNo },
                {
                    $set: { items: [{product_id: 'abc', quantity: 1}] },
                }, 
                { new: true, upsert: true }, 
                (err, res) => {

                    //do_something
                });

Can any one share why we have few documents are getting saved without updated_at?

Upvotes: 2

Views: 1483

Answers (1)

Ashh
Ashh

Reputation: 46461

You need to use option setDefaultsOnInsert: true during the update operation.

Docs

By default, mongoose only applies defaults when you create a new document. It will not set defaults if you use update() and findOneAndUpdate(). However, mongoose 4.x lets you opt-in to this behavior using the setDefaultsOnInsert option.

OrderModel.findOneAndUpdate(
  { order_no: orderNo },
  { $set: { items: [{ product_id: "abc", quantity: 1 }] }},
  { new: true, upsert: true, setDefaultsOnInsert: true }
)

Upvotes: 3

Related Questions