猫鼬需要模型中的模型

Mongoose require model in model

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

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)

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

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

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