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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7419969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:12:18  来源:igfitidea点击:

How do I define methods in a Mongoose model?

javascriptnode.jsmongodbcoffeescriptmongoose

提问by Shamoon

My locationsModelfile:

我的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);

To call it, I'm using:

要调用它,我正在使用:

myLocation.testFunc {locationText: locationText}, (err, results) ->

But I get an error:

但我收到一个错误:

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

回答by pdoherty926

You didn't specify whether you were looking to define class or instance methods. Since others have covered instance methods, here'show you'd define a class/static method:

您没有指定是要定义类方法还是实例方法。既然别人已经覆盖实例方法,这里是你如何定义一个类/静态方法:

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

回答by iZ.

Hmm - I think your code should be looking more like this:

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

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

Then your calling code can require the above module and instantiate the model like this:

然后您的调用代码可以需要上述模块并像这样实例化模型:

 var Location = require('model file');
 var aLocation = new Location();

and access your method like this:

并像这样访问您的方法:

  aLocation.testFunc(params, function() { //handle callback here });

回答by Duncan_m

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

回答by user3573644

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

should be

应该

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

The methods have to be a part of the schema. Not the model.

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