如何在Mongoose模型中定义方法?

我的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' 

您没有指定是否在寻找定义类或实例方法。 由于其他人已经介绍了实例方法,下面是你如何定义一个类方法:

 animalSchema.statics.findByName = function (name, cb) { this.find({ name: new RegExp(name, 'i') }, cb); } 

嗯 – 我认为你的代码应该看起来更像这样:

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

查看有关方法的Mongoose文档

 var animalSchema = new Schema({ name: String, type: String }); animalSchema.methods.findSimilarTypes = function (cb) { return this.model('Animal').find({ type: this.type }, cb); } 
 Location.methods.testFunc = (callback) -> console.log 'in test' 

应该

 LocationSchema.methods.testFunc = (callback) -> console.log 'in test' 

方法必须是模式的一部分。 不是模型。