如何在Mongoose模型中定义方法
How do I define methods in a Mongoose model?
我的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'
您没有指定要定义类方法还是实例方法。由于其他人已经介绍了实例方法,下面是如何定义类/静态方法:
animalSchema.statics.findByName = function (name, cb) {
return this.find({
name: new RegExp(name, 'i')
}, cb);
}
嗯-我认为你的代码应该看起来更像这样:
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 });
请参阅有关方法的Mongoose文档
var animalSchema = new Schema({ name: String, type: String });
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
Location.methods.testFunc = (callback) ->
console.log 'in test'
应该是
LocationSchema.methods.testFunc = (callback) ->
console.log 'in test'
这些方法必须是架构的一部分。不是模型。
相关文章:
- 用于检查数组中是否存在元素的javascript自定义方法
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 如何用Typescript用自定义方法实现类数组
- $resource上带有.then()函数的角度自定义方法导致错误
- 在jquery库中重新定义方法的最佳方法
- 如何将原型用于自定义方法和对象操作
- 续集返回未定义的模型自定义方法
- jQuery 在自定义方法中使用 if 语句进行验证
- NoMethodError ('admin_application_path'的未定义方法)
- 为什么Kendo DataSource使用自定义方法进行端点通信总是发送相同的对象进行删除
- jQuery验证插件-比较两个选择下拉列表的自定义方法
- 理解modal.js中的未定义方法
- 如何在Javascript中向存储类添加自定义方法
- jQuery验证自定义方法规则和具有动态名称的消息
- 使用此 V/s 原型的 Javascript 定义方法
- 要重定向的 SignalR 自定义方法
- 带有base64的回形针:#<字符串:0xb46dba14>的未定义方法“stringify_keys”
- 使用按值删除元素的自定义方法扩展数组
- AngularJS:$resource未调用自定义方法
- 如何在网格.js中添加自定义方法