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

Most upvoted comments

Two solutions:

  1. Use Mixed types as @aheckmann metioned above;
  2. Mongoose Strict Disable the strict option, (enabled by default), ensures that values added to our model instance that were not specified in our schema do not get saved to the db. NOTE: do not set to false unless you have good reason.
    var thingSchema = new Schema({..}, { strict: false });
    var thing = new Thing({ iAmNotInTheSchema: true });
    thing.save() // iAmNotInTheSchema is now saved to the db!!
  1. Adding paths to the model’s schema after the model has been compiled is unsupported. Please don’t do that.
  2. strict mode
  3. When you use discriminator(), you need to pass the same options you passed to CourseSchema and UserSchema. You can change the toJSON and toObject schema options, but not strict. 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.