How do I define methods in a Mongoose model? How do I define methods in a Mongoose model? mongoose mongoose

How do I define methods in a Mongoose model?


You didn't specify whether you were looking to define class or instance methods. Since others have covered instance methods, here's how you'd define a class/static method:

animalSchema.statics.findByName = function (name, cb) {    return this.find({         name: new RegExp(name, 'i')     }, cb);}


Hmm - I think your code should be looking more like this:

var mongoose = require('mongoose'),    Schema = mongoose.Schema,    ObjectId = Schema.ObjectId;var threeTaps = require '../modules/threeTaps';var LocationSchema = new Schema ({   latitude: String,   longitude: String,   locationText: String});LocationSchema.methods.testFunc = function testFunc(params, callback) {  //implementation code goes here}mongoose.model('Location', LocationSchema);module.exports = mongoose.model('Location');

Then your calling code can require the above module and instantiate the model like this:

 var Location = require('model file'); var aLocation = new Location();

and access your method like this:

  aLocation.testFunc(params, function() { //handle callback here });


See the Mongoose docs on methods

var animalSchema = new Schema({ name: String, type: String });animalSchema.methods.findSimilarTypes = function (cb) {  return this.model('Animal').find({ type: this.type }, cb);}