mongo模块导出问题与节点js中的交叉引用文件

时间:2018-07-21 11:58:05

标签: mongoose module-export

我有2个文件Stats.js和Stock.js。这两个文件都需要访问其他文件,因此我必须在Stats中添加require(Stock),反之亦然。但是,在Stats.js中执行createstats()时,它给出的聚合不是Stock中的函数。我发表评论

时没有问题

** var Stats = require('../ Stats'); Stock.js中的行。 **

如何克服此问题。请帮助。谢谢

文件1:Stats.js

var mongoose     = require('mongoose');
var Stock    = require('../Stock');
var logger   = require('../../util/log');
var Schema  = mongoose.Schema;
var StatsSchema   = new Schema({
    item:String,
    pqty:Number,
    sqty:Number,
    date:Date,
});


function createstats () {

    Stock.aggregate([

    .....
    .....
    ])
}
module.exports = mongoose.model('Stats', StatsSchema);

文件2:Stock.js

    var mongoose     = require('mongoose');    
    var Stats    = require('../Stats');
    var logger   = require('../../util/log');
    var Schema       = mongoose.Schema;    

    var StockSchema   = new Schema({
     supplier:String,
     name:Number,
     rate:Number,
     date:Date,   
    });

    function updateqty () {
        Stats.update(

        .....
        .....
        )
    }
    module.exports = mongoose.model('Stock', StockSchema);

1 个答案:

答案 0 :(得分:0)

This is the I have solved the problem. I have added one more file called Schemas.js as below

Schemas.js

 var mongoose     = require('mongoose');    
    var Stats    = require('../Stats');
    var logger   = require('../../util/log');
    var Schema       = mongoose.Schema;    

    var StockSchema   = new Schema({
     supplier:String,
     name:Number,
     rate:Number,
     date:Date,   
    });

var StatsSchema   = new Schema({
    item:String,
    pqty:Number,
    sqty:Number,
    date:Date,
});



module.exports = {
    StatsSchema:StatsSchema,
    StockSchema:StockSchema,
};

then updated file1 and file2 as below

stats.js

 var mongoose     = require('mongoose');
    var logger   = require('../../util/log');

    var modelSchemas = require('../Schemas');
    var StatsSchema=modelSchemas.StatsSchema;
    var StockSchema=modelSchemas.StockSchema;
    Stock = mongoose.model('Stock', StockSchema);
    Stats = mongoose.model('Stats', StatsSchema);


    function createstats () {

        Stock.aggregate([

        .....
        .....
        ])
    }
    module.exports = mongoose.model('Stats', StatsSchema);

stock.js

var mongoose     = require('mongoose');    
    var logger   = require('../../util/log');

var modelSchemas = require('../Schemas');
var StatsSchema=modelSchemas.StatsSchema;
var StockSchema=modelSchemas.StockSchema;

Stock = mongoose.model('Stock', StockSchema);
Stats = mongoose.model('Stats', StatsSchema);

    function updateqty () {
        Stats.update(

        .....
        .....
        )
    }
    module.exports = mongoose.model('Stock', StockSchema);