【问题标题】:findOneAndUpdate doesn't create ObjectIdfindOneAndUpdate 不创建 ObjectId
【发布时间】:2019-02-02 07:09:38
【问题描述】:

我需要发出补丁请求以同时仅更新一个(或多个)字段。 我有一个大对象,它是我的文档,在嵌套的对象数组中。

例如,对于我的汽车阵列,这是架构:

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]
...
});

当我发送更改时,我会这样做:

让 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);

  });
});

我的大问题是我的字段被更新或插入,但如果它被插入并创建一个新数组,它不会创建链接的 objectId。它甚至不会创建对象数组,只是一个具有属性的对象。

如何让猫鼬发起 ObjectId??

【问题讨论】:

  • 请更好地格式化您的帖子。
  • 无法使用 mongodb ObjectId 进行 upsert... objectId 是自动生成的字段,不能在 upsertion 中使用

标签: mongodb express mongoose mongoose-schema


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2021-02-02
    • 2016-04-30
    • 2011-07-04
    • 2021-12-31
    相关资源
    最近更新 更多