Mongoose错误40试图更新createdAt字段

时间:2022-02-05 02:33:15

I have the following model

我有以下型号

const assetSchema = new Mongoose.Schema({
  userID:         { type: ObjectId, required: true, ref: 'User' },
  status:         { type: String,   default: 'active' },
  title:          { type: String,   default: '' },
  description:    { type: String,   default: '' },
  images:         { type: Object,   default: [] },
  videos:         { type: Object,   default: [] },
  comments:       [ Message ],
},
{
  timestamps: true
})

When users create an asset, it will be a draft with only objectId and some other fields with their default values. Then the user will call the edit service as mamy times as needed, and then finally call a separate service to "publish" the asset.

当用户创建资产时,它将是仅具有objectId的草稿和其他具有默认值的字段。然后,用户将根据需要调用编辑服务,然后最终调用单独的服务来“发布”资产。

This is the relevant code of the publish service:

这是发布服务的相关代码:

asset.update({ status: 'active', createdAt: Date.now() }).exec()

This is working with mongodb 2.6, however, after migrating the database to mongodb 3.6 it throws the following error:

这与mongodb 2.6一起使用,但是,在将数据库迁移到mongodb 3.6后,它会抛出以下错误:

{
  name: 'MongoError',
  message: 'Updating the path \'createdAt\' would create a conflict at \'createdAt\'',
  driver: true,
  index: 0,
  code: 40,
  errmsg: 'Updating the path \'createdAt\' would create a conflict at \'createdAt\''
}

The reason I'm updating the createdAt field is because for all use cases the asset's creation date should be the date the user published it, and not the date the user created the draft

我更新createdAt字段的原因是因为对于所有用例,资产的创建日期应该是用户发布它的日期,而不是用户创建草稿的日期

1 个解决方案

#1


0  

I suggest define your own property createdAt in your asset schema.

我建议在资产架构中定义自己的属性createdAt。

Otherwise you can use mongoose-timestamp plugin for mongoose that automatically adds a createdAt property in your documents which is then automatically updated on the document whenever it is saved or updated.

否则,您可以使用mongoose的mongoose-timestamp插件自动在文档中添加createdAt属性,然后在文档保存或更新时自动更新。

More information can be found here : https://www.npmjs.com/package/mongoose-timestamp

更多信息可以在这里找到:https://www.npmjs.com/package/mongoose-timestamp

#1


0  

I suggest define your own property createdAt in your asset schema.

我建议在资产架构中定义自己的属性createdAt。

Otherwise you can use mongoose-timestamp plugin for mongoose that automatically adds a createdAt property in your documents which is then automatically updated on the document whenever it is saved or updated.

否则,您可以使用mongoose的mongoose-timestamp插件自动在文档中添加createdAt属性,然后在文档保存或更新时自动更新。

More information can be found here : https://www.npmjs.com/package/mongoose-timestamp

更多信息可以在这里找到:https://www.npmjs.com/package/mongoose-timestamp