简体   繁体   English

findOneAndUpdate不创建ObjectId

[英]findOneAndUpdate doesn't create ObjectId

I need to make a patch request to update only one (or several) field(s) at the same time. 我需要发出补丁请求才能同时更新一个(或几个)字段。 I've got a big object which is my document, and inside nested array of objects. 我有一个大对象,即我的文档,并且在对象的嵌套数组中。

For example, for my car array, this is the schema : 例如,对于我的car数组,这是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]
...
});

When I send my changes, I do it this way : 当我发送更改时,我是这样进行的:

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

I'm on redux, so my action looks like : 我正在使用redux,因此我的操作如下所示:

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

And my PATCH request is like : 我的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);

  });
});

My BIG issue is that my field is update or inserted, but if it's inserted and it creates a new array it won't create the objectId linked. 我的大问题是我的字段已更新或插入,但是如果插入了字段并创建了一个新数组,则不会创建链接的objectId。 It won't even create the array of object,just an object with a property. 它甚至不会创建对象数组,而只是创建具有属性的对象。

How can I make mongoose initiates ObjectId?? 如何使猫鼬初始化ObjectId?

Per the reply to this SO post it looks like you cannot update object IDs. 根据对此SO帖子的回复,您似乎无法更新对象ID。 When doing so, you are effectively "deleting" the object and creating a new one. 这样做时,实际上是在“删除”对象并创建一个新对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM