【问题标题】:Mongoose sometimes save objectId as string, some times noMongoose 有时将 objectId 保存为字符串,有时没有
【发布时间】:2019-06-23 13:47:27
【问题描述】:

有时 mongoose 将“main_id”保存为字符串而不是 ObjectId,保存后我在 mongoshell 和 UI 客户端中看到字符串类型。

猫鼬:4.11.0

我有架构:

var building = new Schema({
    location: {
        main_id: { type: Schema.Types.ObjectId,  ref: 'locations'},
        title: {type: String},
        description: {type: String}
    },
    year: {type: Number}
});

var User = new Schema({    
    my_location: {
        now: building,
        more: [building]
    }
})

当下面的代码运行时,有时我在 DB 中得到字符串而不是 objectId。

user.my_location.more[i].location.main_id = new mongoose.Types.ObjectId("584fe811ed936fe74d8b470e")
user.save()

当我在保存后检查 typeof user.my_location.more[i].location.main_id 时说“对象”但在 DB 中显示字符串:) 并且当我在 mongoDB 中使用 ObjectId 运行查询时,我找不到这个更新的文档

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    强制告诉猫鼬保存一些东西 (在我的案例中解决了“有时”的问题)

    当我为变量 mongoose 设置类似值的字段时,会检查架构的更改并仅更新它们(正如我从文档中理解的那样),但 mongoose 不会检查嵌套数组的更改。

    所以我们有两个原生技巧:

    1. 强制告诉猫鼬修改了哪个字段

      user.markModified('my_location.more') user.save() //Now all good

    2. 通过set更改数组元素值

      user.my_location.more[i].location.main_id = new mongoose.Types.ObjectId("584fe811ed936fe74d8b470e") user.my_location.more[i].year = 2019 user.my_location.set(i, user.my_location.more) //To set whole changed object user.save()

    【讨论】:

      猜你喜欢
      • 2015-12-13
      • 2017-05-20
      • 2021-05-06
      • 2020-12-03
      • 2018-11-19
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多