I've been trying to find out how to add schema methods in Mongoose which will use model attributes and modify them in some way. Is it possible to make the code below work?
var mySchema = new Schema({
name: {
type: String
},
createdAt: {
type: Date,
default: Date.now
},
changedName: function () {
return this.name + 'TROLOLO';
}
});
MySchema.findOne({ _id: id }).exec(function (error, myschema) {
myschema.changedName();
});
I think so, did you want instance methods? Is that what you meant with Schema methods? If so, you can do something like:
var mySchema = new Schema({
name: {
type: String
},
createdAt: {
type: Date,
default: Date.now
}
});
mySchema.methods.changedName = function() {
return this.name + 'TROLOLO';
};
Something = mongoose.model('Something', mySchema);
With that you can do:
Something.findOne({ _id: id }).exec(function (error, something) {
something.changedName();
});
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