开发者

Why won't my Mongoose model load?

开发者 https://www.devze.com 2023-04-05 13:54 出处:网络
This is my locationsModel.js file: var LocationSchema, LocationsSchema, ObjectId, Schema, mongoose; mongoose = require(\'mongoose\');

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?


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
    }
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消