Gyanesh Gouraw
Gyanesh Gouraw

Reputation: 2021

Dynamic schema keys in Mongoose

I have a simple requirement to get dynamic keys and their values to insert in mongo.

something like this:

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

For this I have created schema as : As I read about [Schema.Types.Mixed],but it only makes datatype of assigned values dynamic ,not the key in my case.

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

module.exports = mongoose.model('DataCollection', myschema);

Can anybody point , whtat is it that I am missing. This is my output,which shows blank value.

Thanks in advance.

enter image description here

Upvotes: 1

Views: 4146

Answers (1)

fqhv
fqhv

Reputation: 1201

I don't think it is possible to literally have a dynamic key as that defeats the purpose of a schema, but you could do something like this:

var KeyValueSchema = new Schema({
    key : String,
    value : String
});

module.exports = mongoose.model('KeyValueCollection', KeyValueSchema); 

Alternatively using the Mixed data type you could store an entire JSON object. For example using this schema:

var mySchema = new Schema({
     data : Schema.Types.Mixed
});

module.exports = mongoose.model('DataCollection', mySchema);

You could insert like:

.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.'});
    });
});

Upvotes: 2

Related Questions