猫鼬在模型中需要模型

时间:2015-06-29 19:09:57

标签: express mongoose static-methods require

我想在模型中使用另一个模型的静态方法。但是当我需要其他模型并调用函数时:

TypeError: Cannot read property 'isCalculated' of undefined

所以..是不是可以在另一个模型中要求模型? :(

模型位于同一个文件夹中,所以我打电话给

var Confirmation = require("./confirmation").Confirmation;

并在确认中输出:

module.exports = {
Confirmation: mongoose.model('Confirmation', confirmationSchema)
};

谢谢:)

更新:代码:invoice.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var autoIncrement = require('mongoose-auto-increment');
var Moment = 'Moment';
var moment = require('moment');
var Currency = mongoose.Types.Currency;
var Confirmation = require("./confirmation.js");
autoIncrement.initialize(mongoose.connection);

var invoiceSchema = new Schema({...}); //invoiceSchema

invoiceSchema.statics.insert= function(invoice, cb) {
....
Confirmation.isCalculated(..) //error here
....
}

module.exports = mongoose.model("Invoice", invoiceSchema);

代码:confirmation.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Invoice = require("./invoice.js");

var confirmationSchema = new Schema({...});

confirmationSchema.statics.isCalculated = function(pid, aid, cb) {...};

module.exports = mongoose.model('Confirmation', confirmationSchema)

1 个答案:

答案 0 :(得分:0)

我的猜测是,由于您的循环导入(confirmation.js需要invoice.js需要confirmation.js ...),Confirmation模型在invoice.js中没有正确实现。

我认为您应该完全删除循环导入并使用mongoose.model()动态获取对“其他”模型的引用,如下所示:

invoiceSchema.statics.insert = function(invoice, cb) {
  ....
  mongoose.model('Confirmation').isCalculated(..)
  ....
}