5

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But as a novice in node programming, which one is better option to choose? I guess for mixed type, I should have a key, which can take up any values.
It's more of a business logic and database schema question rather than a mongoose question. It's not Node specific really unless the question is whether to use Mongoose or the MongoDB driver directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.