【问题标题】:MongoDB (mongoose): Cast to [string] failed for valueMongoDB(猫鼬):转换为 [string] 失败
【发布时间】:2021-11-06 03:25:30
【问题描述】:

当我尝试更新数据库中的文档时发生了错误。

这是架构:

const prodSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  description: {
    type: [String]
  },
})

然后我从别处得到一些产品:

const some_product = axios.get(blah blah)

并更新 mu 文档。 请注意,我为“描述”设置了一个条件:如果它有一个空值,它会被更新 - 否则它保持不变:

const newProduct = {
$set: {
    name: some_product.name,
    description: {
            $cond: {
              if: {
                $eq: [null, '$description']
              },
              then: [some_product.description],
              else: '$description'
            }
    }
}

}

去更新(我用猫鼬): Product.updateOne({name: some_product.name}, newProduct, {some params})

我看到了这个:

转换为 [string] 的值失败 "[{"$cond":{"if":{"$eq":[null,"$description"]},"then":["这里有一些 路径中产品的新描述"],"else":"$description"}}]" “描述”

我认为关键在于模式中的描述类型是字符串数组,而请求的“some_product”中的“描述”字段只是一个字符串。可能是这个问题。

但是我该如何解决呢? 非常感谢。

【问题讨论】:

  • @mohammadNaimi 对不起,我没明白你的意思(

标签: mongodb mongoose


【解决方案1】:
var description = []
description.push(some_product.description)
const newProduct = [{
$set: {
    name: some_product.name,
    description: {
            $cond: {
              if: {
                $eq: [null, '$description']
              },
              then: description,
              else: '$description'
            }
    }
}
}]

将更新操作放入[]使用更新管道 例如 model.update({},[{$set: ...}])

【讨论】:

  • 不,还是一样。我的理论:错误消息说:'...value "[{"$cond":{"if":{"$eq":[null,"$description"]},"then":["这里是对产品的一些新描述"],"else":"$description"}}]"' 它尝试将整个值 '[{"$cond"...' 应用于描述文件。如果在架构中我将 [String] 更改为 Object,则会出现另一个错误:“错误:'description.0.$cond' 中的美元 ($) 前缀字段 '$cond' 对存储无效。”
  • 现在它说“错误:BSON 字段 'update.updates.u' 是错误类型 'array',预期类型 'object'”谷歌没有说清楚。看起来它不喜欢 [array] 文字
  • 能否提供完整的更新代码?
猜你喜欢
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 2017-01-16
  • 2017-10-08
  • 2021-10-25
相关资源
最近更新 更多