How to add a circuit method in mongoose?

I was trying to figure out how to add schema methods to Mongoose that would use the attributes of the model and modify them somehow. Can I make the code below?

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(); }); 
+5
source share
1 answer

I think you need instance methods? Is this what you had in mind 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 this you can:

 Something.findOne({ _id: id }).exec(function (error, something) { something.changedName(); }); 
+5
source

Source: https://habr.com/ru/post/1246979/


All Articles