Reputation: 89
I have this schema (for example):
var WordSchema = new Schema({
word: {
type: String
}
});
module.exports = mongoose.model('Word', WordSchema);
How I can add new property when create new doc in mongoose? something like this:
let Word = require("../models/word");
let initWord = "hello";
word = new Word({
word: initWord,
length: initWord.length
});
word.save(function(error) {
if (error) {
//some code
} else {
//some code
}
});
But this does not work
Upvotes: 4
Views: 2131
Reputation: 22553
By default Mongoose doesn't allow you to dynamically add fields to your document.
But, if you create the schema with the strict option set to false, you can:
var WordSchema = new Schema({
word: {
type: String
}
}, {strict: false});
In order to get at a property that's not in the schema you need to use a special getter form:
doc.get('length')
Or convert the document into a plain old javascript object by calling:
doc.toObject()
on the retrieved schema object.
Upvotes: 5