Mongoose 有时将 objectId 保存为字符串,有时不保存 [英] Mongoose sometimes save objectId as string, some times no
问题描述
有时 mongoose 将main_id"保存为字符串而不是 ObjectId,保存后我在 mongoshell 和 UI 客户端中看到字符串类型.
Sometimes mongoose save "main_id" as string instead of ObjectId, after save I see string type in mongoshell and UI client.
猫鼬: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]
}
})
当下面的代码运行时,有时我在数据库中得到字符串而不是 objectId.
When code below runs sometimes I got string in DB instead 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 运行查询时,我找不到这个更新的文档
When I check typeof user.my_location.more[i].location.main_id
after save is says "object" but in DB show string :) and when I run query in mongoDB with ObjectId I can't found this updated document
推荐答案
强制告诉猫鼬保存一些东西(在我的案例中解决了有时"问题)
当我为变量 mongoose 设置类似值的字段时,会检查架构的更改并仅更新它们(正如我从文档中所理解的那样),但 mongoose 不会检查嵌套数组的更改.
When I set field like value for variable mongoose checks changes for schema and update only them (as I understood from docs) but mongoose don't check nested arrays for changes.
所以我们有两个原生技巧:
So we have two native tricks:
强制告诉猫鼬哪个字段被修改了
Force tell mongoose which field was modified
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 = 2019user.my_location.set(i, user.my_location.more)//设置整个改变的对象user.save()
这篇关于Mongoose 有时将 objectId 保存为字符串,有时不保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!