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

Sha*_*oon 37 javascript mongoose mongodb node.js coffeescript

我的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);
Run Code Online (Sandbox Code Playgroud)

要打电话给我,我正在使用:

myLocation.testFunc {locationText: locationText}, (err, results) ->
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误:

TypeError: Object function model() {
    Model.apply(this, arguments);
  } has no method 'testFunc'
Run Code Online (Sandbox Code Playgroud)

pdo*_*926 43

您没有指定是否要查找类或实例方法.由于其他人已经涵盖了实例方法,因此以下如何定义类/静态方法:

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

  • this.find 没有定义。可能是什么原因? (2认同)

iZ.*_*iZ. 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');
Run Code Online (Sandbox Code Playgroud)

然后你的调用代码可以要求上面的模块并实例化这样的模型:

 var Location = require('model file');
 var aLocation = new Location();
Run Code Online (Sandbox Code Playgroud)

并访问您的方法,如下所示:

  aLocation.testFunc(params, function() { //handle callback here });
Run Code Online (Sandbox Code Playgroud)


Dun*_*n_m 19

请参阅关于方法Mongoose文档

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

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

  • 回答自己,问题是因为我使用了一个Schema方法的箭头函数,它使用了模式的范围,而不是实例模型本身. (2认同)