Mongoose中的dynamic模式密钥

我有一个简单的要求,以获得dynamic密钥和他们的价值插入mongo。

像这样的东西:

[ {"key1": "val1"}, {"key2": "val2"} ] 

为此,我已经创build了模式为:当我读到[Schema.Types.Mixed] ,但它只是使数据types的分配值dynamic,而不是我的情况下的关键。

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var myschema = new Schema({ key: [Schema.Types.Mixed] }); module.exports = mongoose.model('DataCollection', myschema); 

任何人都可以指出,我错过了。 这是我的输出,显示空白值。

提前致谢。

在这里输入图像说明

我不认为有可能从字面上有一个dynamic的关键,因为这会破坏模式的目的,但是你可以这样做:

 var KeyValueSchema = new Schema({ key : String, value : String }); module.exports = mongoose.model('KeyValueCollection', KeyValueSchema); 

或者使用混合数据types,您可以存储整个JSON对象。 例如使用这个模式:

 var mySchema = new Schema({ data : Schema.Types.Mixed }); module.exports = mongoose.model('DataCollection', mySchema); 

你可以插入像:

 .post(function(req, res) { var collection = new DataCollection(); collection.data = {'key' : 'value'}; collection.save(function(err) { if(err) res.send(err); res.json({message:'Data saved to collection.'}); }); });