16

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?

Format:

{
    ObjectId : {
        "attempts" : {
            "response" : String,
            "timestamp" : Date
        },
        "complete" : Boolean
    }
}
Franz Payer
  • 4,069
  • 15
  • 53
  • 77

3 Answers3

15

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
ma08
  • 3,654
  • 3
  • 23
  • 36
3

Update: from 5.1 mongoose have a Map type: https://mongoosejs.com/docs/schematypes.html#maps

rssh
  • 464
  • 4
  • 5
0

You can have your dictionary like this with meta being a dictionary:

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}


});
jamesthakid
  • 1,265
  • 10
  • 11