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

mspsb9vt  于 2023-02-03  发布在  Go
关注(0)|答案(4)|浏览(126)

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

sf6xfgos1#

你没有指定你是要定义类方法还是示例方法。既然其他人已经介绍了示例方法,下面是你应该如何定义类/静态方法:

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

brqmpdu12#

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

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 });
ccgok5k5

ccgok5k53#

请参阅Mongoose方法文档

var animalSchema = new Schema({ name: String, type: String });

animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}
vpfxa7rd

vpfxa7rd4#

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

应该是

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

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

相关问题