使用 Mongoose 创建字典模式 [英] Creating a dictionary schema with Mongoose
问题描述
我正在尝试使用 Mongoose 存储对象字典.意识到我失去了使用 Mixed 类型保存的更改检测,我希望我可以创建一个不需要 Mixed 类型的模式.
I am trying to store a dictionary of objects using Mongoose. Realizing that I lose the change detection for saving with using the Mixed type, I was hoping I could create a schema that would not require the Mixed type.
有很多为对象数组创建模式的例子,但没有为对象字典创建模式.可以这样做吗?
There are plenty of examples of creating schemas for arrays of objects, but not dictionaries of objects. Is it possible to do this?
格式:
{
ObjectId : {
"attempts" : {
"response" : String,
"timestamp" : Date
},
"complete" : Boolean
}
}
推荐答案
mongoose
不支持字典.架构中的字段名称不能是动态的.您应该使用原始对象(嵌入式文档)并将其实现为字典.但是不会有来自 mongoose
的验证,并且在保存之前使用 markModified已更改该字段
There is no support for dictionary in mongoose
. Field name can't be dynamic in a schema. You should go with a raw object(embedded document) and implement it as a dictionary. But there will be no validation from mongoose
and use markModified before saving whenever you have changed that field
var fooSchema=mongoose.Schema({name:String, dic:{}});
//dic is your dictionary
这篇关于使用 Mongoose 创建字典模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!