findOneAndUpdate不会创建ObjectId

时间:2018-08-27 17:45:33

标签: mongodb express mongoose mongoose-schema

我需要发出补丁请求,才能一次仅更新一个(或几个)字段。 我有一个很大的对象就是我的文档,并且在对象的嵌套数组中。

例如,对于我的汽车阵列,这是模式:

const carSchema = new Schema({
  owner: [{value: {type: String}, label: {type: String}}],
  carPlate: {type: String},
  carColor: {type: String},
  carBrand: {type: String},
  carStatus: {type: String}
});

const myObject = new Schema({
...
cars: [carSchema]
...
});

当我发送更改时,我是这样进行的:

let dynamicVar ='cars。'+ i +'。'+ myfield; this.props.updateGeneral({_ id:this.props.general._id,[dynamicVar]:[myfield.value]});

我正在使用redux,所以我的操作如下:

export function updateGeneral(data) {
    let _id = data._id;
    delete data._id;
    return {
        type: 'UPDATE_GENERAL',
        payload: client.patch(`${url}/${_id}`, data)
    }
}

我的PATCH请求就像:

router.patch('/url/:id', async (req, res, next) => {
myObject.findOneAndUpdate({_id: req.params.id}, {$set: req.body }, {upsert: true, new: true}, function (err, objectReturn) {
    if (err) return next(err);
    cn = cn.substr(0, cn.indexOf(' {'));
    res.json(objectReturn);

  });
});

我的BIG问题是我的字段已更新或插入,但是如果将其插入并创建新数组,则不会创建链接的objectId。它甚至不会创建对象数组,而只是创建具有属性的对象。

如何让猫鼬初始化ObjectId?

1 个答案:

答案 0 :(得分:0)

根据对this SO post的答复,您似乎无法更新对象ID。这样做时,实际上是在“删除”该对象并创建一个新对象。

相关问题