1

This is my locationsModel.js file:

var LocationSchema, LocationsSchema, ObjectId, Schema, mongoose;
mongoose = require('mongoose');
Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;
LocationSchema = {
  latitude: String,
  longitude: String,
  locationText: String
};
LocationsSchema = new Schema(LocationSchema);
LocationsSchema.method({
  getLocation: function(callback) {
    return console.log('hi');
  }
});
exports.Locations = mongoose.model('Locations', LocationsSchema, 'locations');

In my controller, I have:

var Locations, mongoose;
mongoose = require('mongoose');
Locations = require('../models/locationsModel').Locations;
exports.search = function(req, res) {
  var itemText, locationText;
  Locations.getLocation('info', function(err, callback) {
    return console.log('calleback');
  });
  return;
};

When I run it, I get the following error:

TypeError: Object function model() {
    Model.apply(this, arguments);
  } has no method 'getLocation'

What am I missing?

1
  • In your controller instead of Locations = require('../models/locationsModel').Locations; you can simply go Locations = mongoose.model('Locations') Jan 11, 2013 at 1:47

1 Answer 1

3

I think what you're after is statics rather than a method.

As per the docs:

I think you should define the getLocations function as follows (looking at your use of getLocations you've got a string parameter as well as the callback:

LocationsSchema.statics.getLocation = function(param, callback) {
    return console.log('hi');
}

EDIT:

The difference between statics and methods is whether you are calling it on the "type" or "objects" of that type. Adapted from the examples:

BlogPostSchema.methods.findCreator = function (callback) {
  return this.db.model('Person').findById(this.creator, callback);
}

which you'd invoke as such:

BlogPost.findById(myId, function (err, post) {
  if (!err) {
    post.findCreator(function(err, person) {
      // do something with the creator
    }
  }
});
1
  • Thank you so much! Wow - awesome! So when would I use a static vs a method?
    – Shamoon
    Sep 16, 2011 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.