Mongodb Mongoose有时将objectId保存为字符串,有时不保存
有时候mongoose会将“main_id”保存为字符串而不是ObjectId,保存后我会在mongoshell和UI客户端中看到字符串类型 猫鼬:4.11.0 我有一个模式:Mongodb Mongoose有时将objectId保存为字符串,有时不保存,mongodb,mongoose,Mongodb,Mongoose,有时候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}, descriptio
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()
当我在保存后检查user.my_location.more[I].location.main_id的类型时,显示为“object”,但在DB show string:)中,当我使用ObjectId在mongoDB中运行查询时,我找不到这个更新的文档强制告诉mongoose保存某些内容 (解决了我的“有时”问题) 当我为变量设置类似字段的值时,mongoose会检查模式的更改并只更新它们(正如我从文档中理解的那样),但mongoose不会检查嵌套数组的更改 所以我们有两个本地技巧:
user.markModified('my_location.more'))
user.save()//现在一切正常
set
user.my_location.more[i].location.main_id=new mongoose.Types.ObjectId(“584fe811ed936fe74d8b470e”)
user.my_location.more[i].year=2019
user.my\u location.set(i,user.my\u location.more)//设置整个已更改的对象
user.save()