mongoose: Dynamically adding fields in the schema doesn't permit to add fields as usual
Hi,
When I dynamically add a field to a schema and instantiate it to a model, mongoose is not aware of any change made on this new field when I call save.
var schema = new mongoose.Schema({
name: String,
firstname: String
});
var person = db.model('persons', schema);
var a = new person();
a.name = "John";
a.firstname = "Doh";
a.save(function(err, savedGuy) {
schema.add({
field1: String
});
// schema is now updated with the field1
var personV2 = db.model('persons', schema);
personV2.findById(savedGuy['_id'], function(err, john) {
// won't work
john.field1 = 'Custom field 1 value';
// will work
john.set ('field1', 'Custom field 1 value');
});
});
I create dynamic but persistent schemas in my project. I can’t fill any data until I restart node. It looks like a bug for me. The purpose of schema.add function should be to avoid the use of set() which seems useful only for arrays properties that can’t be detected by mongoose.
I need right now to intensively manipulating objects which is not pretty at all. So my questions are : is this an issue ? If so, is this possible to think about a fix ?
Best regards and thank you for your work !
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Reactions: 1
- Comments: 16
Two solutions:
discriminator()
, you need to pass the same options you passed toCourseSchema
andUserSchema
. You can change thetoJSON
andtoObject
schema options, but notstrict
. Admittedly this is somewhat cumbersome and will likely change in the future (#3414). For more information on discriminators, check out my blog post on discriminators.by design. schemas are compiled into models and are not “live”. if you aren’t sure about your schema you can always used Mixed types.