Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic schema using mongoose

I'm very new to Node js and Mongoose module. I'm trying to create a schema, where there are some required fields and some others can be dynamic.

I have used strict to false. My code looks like this:

var mongoose = require('mongoose')
var db = mongoose.connect('mongodb://localhost/ets',function(err)
{
    if(err) throw err
})

var Schema = mongoose.Schema
var Tasks = new Schema({vmProfile:String}, { strict: false });
mongoose.model('Task',Tasks)

var Task = mongoose.model('Task')
var task = new Task()
task.vmProfile = "required value"
task.otherKey = "something"
task.save(function(err)
{
    if(err) throw err;
})

when I run this , I get only the vmProfile saved, not otherKey, the DB looks like this:

{ "vmProfile" : "required value", "_id" : ObjectId("53364a5a5cd71a76122f0a8a"), "__v" : 0 }

where I'm making the mistake.

like image 407
sriram Avatar asked Nov 10 '22 10:11

sriram


1 Answers

From the Mongoose docs:

NOTE: Any key/val set on the instance that does not exist in your schema is always ignored, regardless of schema option.

You can set the value when the model instance is created:

var task = new Task({'otherKey', 'some value'});

You could also put the ad-hoc values under a mixed subdocument type as well.

like image 70
WiredPrairie Avatar answered Nov 14 '22 23:11

WiredPrairie