【问题标题】:How do I define methods in a Mongoose model?如何在 Mongoose 模型中定义方法?
【发布时间】:2011-11-17 05:04:10
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js mongodb coffeescript mongoose


    【解决方案1】:

    您没有指定是要定义类方法还是实例方法。由于其他人已经涵盖了实例方法,here's 你将如何定义类/静态方法:

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

    【讨论】:

    • 只是为了完成您的答案,这是使用示例(来自同一页面):var Animal = mongoose.model('Animal', animalSchema); Animal.findByName('fido', function (err, animals) {console.log(animals)});
    • 静态万岁!这就是我一直在寻找的
    • this.find 未定义。可能是什么原因?
    【解决方案2】:

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

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

    【讨论】:

    • 对不起,如果我在这里误读,但我看不出这与 OPs 代码有何不同。
    • 可以使用 mongoDB shell 以某种方式使用相同的方法吗?
    • @Will,我认为不同之处在于 iZ。正在将函数应用于模式而不是模型。
    【解决方案3】:

    见Mongoose docs on methods

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

    【讨论】:

    • 问题是,在我执行时,我收到“animal.findSimilarTypes is not a function”消息!
    • 就我而言,与完全相同的示例this.model 未定义。知道为什么吗?
    • 回答我自己,问题是因为我对其中一个 Schema 方法使用了箭头函数,它使用的是模式的范围,而不是实例模型本身。
    【解决方案4】:
    Location.methods.testFunc = (callback) ->
      console.log 'in test'
    

    应该是

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 2020-10-17
      • 2016-12-21
      • 2019-03-18
      • 2012-09-07
      • 2021-03-18
      • 2012-04-15
      • 1970-01-01
      • 2019-02-17
      相关资源
      最近更新 更多