插入默认值不起作用mongodb [英] Insert default values not working mongodb
问题描述
我正在使用猫鼬版本5.2.5
,这是我的订单的示例模型
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' });
我在猫鼬save
和findOneAndUpdate
的主脚本中使用以上模型.
在生产系统中,我们看到许多文档在保存文档中没有last_updated
键.
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.
以下是我们的主脚本中猫鼬save
方法和findOneAndUpdate
的示例代码.我们看到有些文档具有updated_at
键,而保存文档时很少有它们.
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
});
任何人都可以分享为什么没有updated_at
就能保存很少的文档吗?
Can any one share why we have few documents are getting saved without updated_at
?
推荐答案
您需要使用选项update操作期间进行nofollow noreferrer> setDefaultsOnInsert: true
.
You need to use option setDefaultsOnInsert: true
during the update
operation.
默认情况下,猫鼬仅在创建新的时应用默认设置 文档.如果您使用update()和 findOneAndUpdate().但是,猫鼬4.x可让您选择加入 使用setDefaultsOnInsert选项的行为.
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 }
)
这篇关于插入默认值不起作用mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!