Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add schema method in mongoose? [duplicate]

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();
});
like image 703
prototype Avatar asked Apr 12 '16 22:04

prototype


1 Answers

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();
});
like image 134
Daniel Sandiego Avatar answered Sep 28 '22 19:09

Daniel Sandiego