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

49

我的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'
4个回答

51

您没有指明您是要定义类方法还是实例方法。由于其他人已经介绍了实例方法,在这里介绍如何定义一个类/静态方法:

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

1
只是为了完善你的答案,这是用法示例(来自同一页): var Animal = mongoose.model('Animal', animalSchema); Animal.findByName('fido', function (err, animals) {console.log(animals)}); - Wax Cage
太好了,静态的!这正是我在寻找的。 - Vaiden
2
this.find 未定义。可能的原因是什么? - Ramesh Pareek

33

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

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

抱歉如果我理解有误,但我不明白这与原帖中的代码有何不同。 - Will
同样的方法是否可以在mongoDB shell中使用? - p0lAris
@Will,我认为区别在于iZ.将函数应用于模式而不是模型。 - kim3er

20

请参考Mongoose官方文档中的方法部分

var animalSchema = new Schema({ name: String, type: String });

animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}

1
问题是,在我的执行中,我收到了“animal.findSimilarTypes不是一个函数”的消息! - ramazan polat
在我的情况下,使用完全相同的示例this.model是未定义的。有什么想法为什么会这样? - Carlos Pinto
3
我发现问题出在一个 Schema 方法中使用了箭头函数,这个箭头函数使用了 Schema 的作用域而不是实例模型本身的作用域。我修改了该函数,确保它能够正确地使用实例模型的作用域。 - Carlos Pinto

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

应该是

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接