【问题标题】:Mongoose: "Cast to embedded failed" error when updating by pushing an object to arrayMongoose:通过将对象推送到数组进行更新时出现“转换为嵌入式失败”错误
【发布时间】:2020-02-23 21:34:05
【问题描述】:

我正在尝试通过将对象添加到对象数组来更新文档。数组是文档的属性。错误信息很简单:

CastError: Cast to embedded failed for value

+ 我要推动的物体。这不是很具有描述性或帮助性。

这是我的架构:

const timeoff = new Schema(
  {
    requestId: {
      type: Number,
      unique: true
    },
    // ... some other properties
    approvals: [{
      email: String,
      status: String,
      lastChangedStatus: Date,
      lastNotificationSent: Date
    }]
  },
  {
    usePushEach: true
  }
);

这就是我尝试将approval 对象添加到approvals 数组的方式:

await this.findOneAndUpdate({ requestId }, { $push: { 'approvals': approval } });

这是我提供的 approval 对象:

  const approval = {
    email: 'test@example.com',
    status: 'pending',
    lastChangedStatus: 'requested',
    lastNotificationSent: this.moment().format('YYYY-MM-DD') // which ends as '2019-10-28'
  };

这是完整的错误:

CastError: 值 "{\n' + 转换为嵌入失败 " 电子邮件:'test@example.com',\n" + " 状态: '待定',\n" + " lastChangedStatus: '请求',\n" + " lastNotificationSent: '2019-10-28'\n" + '}" 在路径“批准”

所以,我不确定如何处理这个问题。属性中的数据类型与模式的属性类型正确匹配。还有什么问题?

猫鼬:^5.7.4

mongodb:4.2.0

【问题讨论】:

  • 尝试定义为新模式。所以:approvals: [new Schema({email: String, status: String, lastChangedStatus: Date, lastNotificationSent: Date})]

标签: mongodb mongoose


【解决方案1】:

在架构lastChangedStatus: Date 中,它是Date 属性。但是,在您的 approval 对象中,它是一个 String。我相信这是卡住的地方。

【讨论】:

    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 2019-03-28
    • 2019-04-08
    • 2018-07-12
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多