猫鼬更新中的单个数组(如果不存在)

时间:2020-04-11 15:45:46

标签: node.js mongodb mongoose

model
state: [ {
        type: String,
        require: true
    }]

states = ['Gujarat','Rajasthan'];
state.findOneAndupdate({'_id':id},{state:states});

如果存在覆盖,如何更新?

我想在模型中存储

states:['Gujarat','Rajstan','Amreli']

1 个答案:

答案 0 :(得分:1)

使用$addToSet$each修饰符可以在mongodb中唯一地更新数组字段:

查询:

let states = ["Gujarat", "Rajasthan"];

db.state.update({ _id: id }, { $addToSet: { state: { $each: states } } });