Mongodbdynamic模式保存任何数据

我们经常像这样定义一个模式

var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Account = new Schema({ username: String, password: String }); module.exports = mongoose.model('account', Account); 

我们必须传入匹配模式的对象,否则什么都不起作用。 但是说我想保存一些dynamic的东西,我甚至不知道它是什么,例如它可以

 {'name':'something',birthday:'1980-3-01'} 

或者其他任何东西

 {'car':'ferrari','color':'red','qty':1} 

那么你如何设置模式呢?

Mongoose有一个Mixed 模式types ,允许一个字段是任何对象。

 var Account = new Schema({ username: String, password: String, anyobject: Schema.Types.Mixed }); 

您可以使用strict: false选项将现有模式定义作为Schema构造函数中的第二个参数提供:

 var AccountSchema = new Schema({ Name : {type: String}, Password : {type: String} }, {strict: false}); module.exports = mongoose.model('Account', AccountSchema); 

您也可以使用Mixedtypes

 var TaskSchema = new Schema({ Name : {type: String}, Email : {type: String}, Tasks : [Schema.Types.Mixed] }, {strict: false}); module.exports = mongoose.model('Task', TaskSchema);