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'
클래스 또는 인스턴스 메서드를 정의할지 여부를 지정하지 않았습니다.다른 인스턴스 메소드도 포함되어 있으므로 클래스/정적 메소드를 정의하는 방법은 다음과 같습니다.
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 });
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'
메서드는 스키마의 일부여야 합니다.모델이 아닙니다.
언급URL : https://stackoverflow.com/questions/7419969/how-do-i-define-methods-in-a-mongoose-model
'programing' 카테고리의 다른 글
| Azure WebJob 시간 초과 구성 설정 (0) | 2023.05.22 | 
|---|---|
| 비동기/대기로 파일을 올바르게 읽는 방법은 무엇입니까? (0) | 2023.05.22 | 
| 푸시되지 않은 기존 커밋 메시지를 수정하는 방법은 무엇입니까? (0) | 2023.05.22 | 
| Is Nothing 대 Is Nothing (0) | 2023.05.22 | 
| varchar 필드 유형을 정수로 변경합니다. "정수 유형으로 자동 캐스트할 수 없습니다." (0) | 2023.05.22 |