Reputation: 610
I have the following code:
var Schema = mongoose.Schema;
var personSchema = new Schema({
firstname: String,
lastname: String,
address: String,
});
var Person = mongoose.model('humans', personSchema);
var john = Person({ //will turn into a new object.
firstname: "john",
lastname: "doe",
address: "somewhere",
});
//save the user
john.save(function(err){
if(err) throw err;
console.log('person saved!');
});
now, in my database, I have a collection called humans with firstname: "john", lastname: "doe", address: "somewhere", as you can see above. My question is: is there a way that inside the humans collection, there will be 1 document that will have the structure you see above, and one with some new fields:
firstname: String,
lastname: String,
address: String,
car: String,
office: String
I have tried a couple of ways to redefine the structure of the personSchema but it's always giving me the same error, Cannot overwrite model once compiled.”
Thank you for your time.
Upvotes: 0
Views: 631
Reputation: 613
The error is occurring because you already have a schema defined, and then you are defining the schema again. Instantiate the schema once and the make Global object to access schema.
Change your Person schema, and add new fields
var personSchema = new Schema({
firstname: String,
lastname: String,
address: String,
car: String,
office: String
});
Documents which does not contain added fields after populating will have this keys but with undefined values.
For not ignoring new properties you can unstrict schema
var personSchema = new Schema({
firstname: String,
lastname: String,
address: String,
car: String,
office: String
}, {strict: false});
Also you can use Mixed type to set anything to property
var personSchema = new Schema({
firstname: String,
lastname: String,
additional: Mixed
});
And set other properties in additional field.
Upvotes: 1