【问题标题】:Replace all instances of "null" with null将“null”的所有实例替换为 null
【发布时间】:2021-01-02 10:25:31
【问题描述】:

将数据导入 mongo 后,本应为 null 类型的字段最终成为字符串“null”,是否有命令或查询将该字符串的所有实例替换为 null 值?

我有这样的事情

TestModel.updateMany({ test: 'null' },{ $set: { test: null } })

但是它会抛出这个错误

CastError: Cast to ObjectId failed for value "null" at path "test" for model "TestModel"

我在其他都是字符串的字段中尝试过它并且它可以工作,但是字段“test”可以是 Objectid 或 null

编辑:

文档:

const TestSchema = new Schema({
    test: { type: Schema.Types.ObjectId}
});
module.exports = db.model('TestModel', TestSchema);

【问题讨论】:

  • 请发布显示test 字段的示例文档。此外,请指定从何处运行此命令(shell、节点、Mongoose 等)。
  • @prasad_ 我尝试使用 mongoose 运行该命令,但我正在寻找关于 mongoose 或 shell 的解决方案
  • 该命令可以使用 shell。 Mongoose 正在尝试将“null”转换为 objectId,shell 不会。 db.TestModel.updateMany({ test: 'null' },{ $set: { test: null } }, {multi: true})
  • 是否需要明确设置为null,或者从文档中省略该字段是否足够?

标签: mongodb mongodb-query node-mongodb-native mongodb-compass


【解决方案1】:

使用此代码:

TestModel.updateMany({ test: 'null' }, { $set: { test: undefiend } })

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 2022-10-23
    相关资源
    最近更新 更多