如何在Mongoose模型中定义方法? [英] How do I define methods in a Mongoose model?
本文介绍了如何在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'
推荐答案
您没有指定是否要查找定义类或实例方法。由于其他人已涵盖实例方法,因此此处如何定义类方法:
You didn't specify whether you were looking to define class or instance methods. Since others have covered instance methods, here's how you'd define a class method:
animalSchema.statics.findByName = function (name, cb) {
this.find({
name: new RegExp(name, 'i')
}, cb);
}
这篇关于如何在Mongoose模型中定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文