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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With