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.
我正在尝试使用Mongoose存储对象字典。意识到我丢失了使用Mixed类型进行保存的更改检测,我希望我可以创建一个不需要Mixed类型的模式。
There are plenty of examples of creating schemas for arrays of objects, but not dictionaries of objects. Is it possible to do this?
有很多为对象数组创建模式的示例,但不是对象的字典。是否有可能做到这一点?
Format:
格式:
{
ObjectId : {
"attempts" : {
"response" : String,
"timestamp" : Date
},
"complete" : Boolean
}
}
2 个解决方案
#1
10
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
在猫鼬中不支持字典。字段名称在架构中不能是动态的。您应该使用原始对象(嵌入文档)并将其实现为字典。但是,无论何时更改该字段,都不会从mongoose进行验证并在保存之前使用markModified
var fooSchema=mongoose.Schema({name:String, dic:{}});
//dic is your dictionary
#2
0
You can have your dictionary like this with meta being a dictionary:
您可以使用meta作为字典来使用这样的字典:
var UserSchema = new Schema({
meta: {
votes: Number,
favs: Number
}
first_name: String,
last_name: String,
profile_pic: String,
gender: String,
timezone: Number
date: { type: Date, default: Date.now },
updated: { type: Date, default: Date.now },
country: {id: Number, name: String}
});
#1
10
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
在猫鼬中不支持字典。字段名称在架构中不能是动态的。您应该使用原始对象(嵌入文档)并将其实现为字典。但是,无论何时更改该字段,都不会从mongoose进行验证并在保存之前使用markModified
var fooSchema=mongoose.Schema({name:String, dic:{}});
//dic is your dictionary
#2
0
You can have your dictionary like this with meta being a dictionary:
您可以使用meta作为字典来使用这样的字典:
var UserSchema = new Schema({
meta: {
votes: Number,
favs: Number
}
first_name: String,
last_name: String,
profile_pic: String,
gender: String,
timezone: Number
date: { type: Date, default: Date.now },
updated: { type: Date, default: Date.now },
country: {id: Number, name: String}
});