Mongoose: CastError: Cast to embedded failed for value "{ value: 'x' }" at path "items"

Mongoose: CastError: Cast to embedded failed for value "{ value: 'x' }" at path "items"

更新到 Mongoose 5.11.13 后,我在尝试将项目添加到文档内的子对象时收到以下错误。

CastError: Cast to embedded failed for value "{ value: 'new item' }" at path "items"
    at model.Query.exec (D:\repos\pushbox\node_modules\mongoose\lib\query.js:4358:21)
    at model.Query.Query.then (D:\repos\pushbox\node_modules\mongoose\lib\query.js:4452:15)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  messageFormat: undefined,
  stringValue: `"{ value: 'new item' }"`,
  kind: 'embedded',
  value: "{ value: 'new item' }",
  path: 'items',
  reason: TypeError: this.ownerDocument(...).isSelected is not a function

我的主要 Schma 叫做 Card。它包含一个名为 Property 的 sub-object/sub-document,它看起来像这样:

export const CardSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },

  description: {
    type: String,
    default: '',
  },

  // Checklists in a Card
  checklists: [{
    title: {
      type: String,
      required: true,
    },
    items: [{
      name: String,
      select: Boolean,
    }],
  }],
 // Properties in a card
  properties: [{
    name: {
      type: String,
      required: true,
    },
    items: [{
      value: { type: String, default: '' },
      isSelected: { type: Boolean, default: false },
    }],
  }],

  box: {
    type: ObjectId,
    ref: 'Box',
  },
}, {
  timestamps: { createdAt: true, updatedAt: true },
});

用于在 property 中插入新 item 的查询是:

const newPropItem = await Card.findOneAndUpdate(
        {
          _id: cardId,
          'properties._id': propertyId,
        },
        {
          $push: {
            'properties.$.items': { value: newItem.trim() },
          },
        },
        {
          new: true,
        },
      );

我不知道为什么会这样,因为我们对 Checklist 有一个类似的查询并且它有效。我在 mongo shell 中尝试了这个查询,它在那里工作。你们能帮我弄清楚我到底错过了什么吗?

哦,我也尝试查看整个 TypeError: this.ownerDocument(...).isSelected is not a function 部分,但没有找到任何对我的情况有帮助的东西

您不能在 Schema 中使用 isSelected 作为字段名称,因为 isSelected() 在内部用于检查我们需要在 mongoose 中验证哪些路径,因此请更改 filed 名称为 isSelect 或 ...