如何在Mongoose模型中定义方法

How do I define methods in a Mongoose model?

本文关键字:定义 方法 模型 Mongoose      更新时间:2023-09-26

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

这些方法必须是架构的一部分。不是模型。