我的locationsModel
文件:
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);
要打电话,我正在使用:
myLocation.testFunc {locationText: locationText}, (err, results) ->
但是我收到了一个错误:
TypeError: Object function model() {
Model.apply(this, arguments);
} has no method 'testFunc'
答案 0 :(得分:42)
您没有指定是否要查找类或实例方法。由于其他人已经涵盖了实例方法,here's如何定义类/静态方法:
animalSchema.statics.findByName = function (name, cb) {
this.find({
name: new RegExp(name, 'i')
}, cb);
}
答案 1 :(得分:27)
嗯 - 我认为你的代码看起来应该更像这样:
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');
然后你的调用代码可以要求上面的模块并实例化这样的模型:
var Location = require('model file');
var aLocation = new Location();
并按如下方式访问您的方法:
aLocation.testFunc(params, function() { //handle callback here });
答案 2 :(得分:17)
var animalSchema = new Schema({ name: String, type: String });
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
答案 3 :(得分:1)
Location.methods.testFunc = (callback) ->
console.log 'in test'
应该是
LocationSchema.methods.testFunc = (callback) ->
console.log 'in test'
方法必须是架构的一部分。不是模特。