Mongodb mongoose:如果值为“0”,则不更新&引用;但不要更新其他内容
当更新一条记录时,如果值为“”,现有值将被覆盖,我不希望它被Mongodb mongoose:如果值为“0”,则不更新&引用;但不要更新其他内容,mongodb,mongoose,Mongodb,Mongoose,当更新一条记录时,如果值为“”,现有值将被覆盖,我不希望它被 const company = "myCo" const name = "someName" const description = ''; const image = '' const updated = await assetClasses .updateOne( { company, name }, {
const company = "myCo"
const name = "someName"
const description = '';
const image = ''
const updated = await assetClasses
.updateOne(
{ company, name },
{
$set: {
description,
image,
},
},
{
upsert: true,
}
)
.exec();
数据看起来像
_id:5e38002a56fa5e54f1fe10de
indistructable:false
company:"myCo"
description:"dont overwrite me"
image:"myimage.png"
name:"someName"
supply:10000
createdAt:2020-02-03T11:12:42.371+00:00
updatedAt:2020-02-03T13:21:35.924+00:00
__v:0
我开发了一些变体,假设您只想避免空字符串,所以这就是关于字符串的 变量1(接受非空字符串;如果为空-从db获取现有值): 变体2(与1相同,更简单): 变体3(编辑模型,不允许存储空字符串): 例如,如果您的猫鼬模型看起来像:
{
...
description: String,
image: String
}
然后,您只需添加额外的规则:
{ ...
description: {
type: String,
minlength: 1
},
image: {
type: String,
minlength: 1
}
}
在更新查询中,您需要传递选项runValidators
{runValidators:true}
您也可以将变体1/2与3结合使用
资料来源:
{
...
description: String,
image: String
}
{ ...
description: {
type: String,
minlength: 1
},
image: {
type: String,
minlength: 1
}
}