简体   繁体   中英

No set type for mongoose model variable

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM