为什么我的Mongoose模型不能加载?

这是我的locationsModel.js文件:

 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'); 

在我的控制器中,我有:

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

当我运行它时,出现以下错误:

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

我错过了什么?

我认为你所追求的是静态而不是方法。

根据文档 :

我想你应该定义getLocations函数,如下所示(查看你使用的getLocations你有一个string参数以及callback:

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

编辑:

staticsmethods之间的区别在于,您是否在该types的“types”或“对象”上调用它。 从这些例子改编而来:

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

你会这样调用:

 BlogPost.findById(myId, function (err, post) { if (!err) { post.findCreator(function(err, person) { // do something with the creator } } });