Home > OS >  No set type for mongoose model variable
No set type for mongoose model variable

Time:09-11

I have this schema in mongoose

var data = new Schema({
    Plan:String,
    Key:String,
    Uses:Number,
    UsesLeft:Number,
    AddedOn:Date,

}); 

But I want Key to be anything, such as an object, string, or number.

Is there any way to not set a type to it and set it to something later when creating a document?

Such as this

var data = new Schema({
    Plan:String,
    Key:Anything,
    Uses:Number,
    UsesLeft:Number,
    AddedOn:Date,

}); 

Thanks

CodePudding user response:

Yes, there's a way to this using the Mongoose mixed schema

Using your example, you'll have something like

const data = new Schema({ any: mongoose.Mixed }); 

You can add anything to it with your code.

Since Mixed is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To tell Mongoose that the value of a Mixed type has changed, you need to call doc.markModified(path), passing the path to the Mixed type you just changed. - from the docs.

  • Related