简体   繁体   中英

How do I define methods in a Mongoose model?

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'

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);
}
Location.methods.testFunc = (callback) ->
  console.log 'in test'

should be

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

The methods have to be a part of the schema. Not the model.

Methods in Mongoose models are defined as properties of the model's prototype.

Here is an example of how you can modify the code to correctly define the method in your model:

 LocationSchema = new Schema({ latitude: String, longitude: String, locationText: String }); LocationSchema.methods.testFunc = function (callback) { console.log('in test'); }; const Location = mongoose.model('Location', LocationSchema);

And to call the method:

 const myLocation = new Location({ locationText: locationText }); myLocation.testFunc(function(err, results) { //... });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM