Insert default values not working mongodb

ぃ、小莉子 提交于 2019-12-11 07:26:56

问题


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?


回答1:


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 }
)


来源:https://stackoverflow.com/questions/56140964/insert-default-values-not-working-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!