这是我的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'
我错过了什么?
答案 0 :(得分:3)
我认为你所追求的是静力而不是方法。
根据docs:
我认为您应该定义getLocations
函数如下(查看您使用getLocations
您是否有字符串参数以及回调:
LocationsSchema.statics.getLocation = function(param, callback) {
return console.log('hi');
}
编辑:
statics
和methods
之间的区别在于您是在该类型的“类型”还是“对象”上调用它。改编自examples:
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
}
}
});