2011-09-14 4 views
32

マイlocationsModelファイル:Mongooseモデルでメソッドを定義するにはどうすればよいですか?

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' 

答えて

24

うーん - 私はあなたのコードがあるべきだと思いますこれ以上のように見える:

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

申し訳ありませんが、私はここで誤読していますが、これはOPコードとどのように違うのか分かりません。 – Will

+0

同じ方法を何とかmongoDBシェルを使って使用できますか? – p0lAris

+0

@ウィル、私は違いがiZだと思う。モデルではなくスキーマに関数を適用しています。 – kim3er

15

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

+1のドキュメントへのリンク – allenhwkim

+1

問題は、私の実行では、 "animal.findSimilarTypesは関数ではありません"というメッセージです! –

+0

私の場合、まったく同じ例では、 'this.model'は未定義です。どんな考え? –

35

を参照してください。クラスメソッドとインスタンスメソッドのどちらを定義するかは指定していません。他の人がインスタンスメソッドをカバーしているので、あなたはクラス/静的メソッドを定義したいかhere's

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

答えを完成させるだけです(同じページから): 'var Animal = mongoose.model( 'Animal'、animalSchema);' Animal.findByName( 'fido'、function(err、animals){console .log(animals)}); –

+0

静けさのための万歳!私が探していたもの – Vaiden

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

は、方法は、スキーマの一部である必要はあり

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

でなければなりません。モデルではありません。

関連する問題