How do I define methods in a Mongoose model?


Question

My locationsModel file:

mongoose = require 'mongoose'
threeTaps = require '../modules/threeTaps'

Schema = mongoose.Schema
ObjectId = Schema.ObjectId

LocationSchema =
  latitude: String
  longitude: String
  locationText: String

Location = new Schema LocationSchema

Location.methods.testFunc = (callback) ->
  console.log 'in test'


mongoose.model('Location', Location);

To call it, I'm using:

myLocation.testFunc {locationText: locationText}, (err, results) ->

But I get an error:

TypeError: Object function model() {
    Model.apply(this, arguments);
  } has no method 'testFunc'
1
37
6/30/2015 8:47:22 PM

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) {
    this.find({ 
        name: new RegExp(name, 'i') 
    }, cb);
}
43
2/11/2018 3:05:16 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon