我的以下代码需要在两个文件中使用:

var Schema = mongoose.Schema;

var InfoSchema = new Schema ({
    name: String,
    email: String,
});

var Info = mongoose.model('Info', InfoSchema);


我需要在listTerminal.js中使用Info变量,并且需要在route.js中使用InfoSchema。

我是Node.js的新手,但我仍然对module.exports感到困惑。谁能给我个灯?

我试图这样做:

module.exports = function() {
    var Schema = mongoose.Schema;

    var InfoSchema = new Schema ({
        name: String,
        email: String,
    });
};


他们在我的route.js和listTerminal.js中这样调用:

var mySchema = require('../config/mongo/mySchema');


但是不起作用,因为在我的route.js中,我有这样的路由:

app.post('/person', function(req, res) {
    var Data = {
        name: req.body.name,
        email: req.body.email
    };

    var info = new Info(Data);

    info.save(function (error, data){
        if (error) {
            console.log(error);
        }
        else {
            console.log('done');
        }
    });
});


页面显示:

Info is not defined


如何在另一个文件中调用此mySchema.js?

OBS:如果我将myschema.js代码移到我的route.js文件中,则route.js可以工作,但是我需要单独使用; [

最佳答案

您的模块应如下所示:

var Schema = mongoose.Schema;

var InfoSchema = new Schema ({
    name: String,
    email: String,
});

module.exports = mongoose.model('Info', InfoSchema);


这样,您将导出模型,而不是模式。然后,您可以像这样使用它:

var Info = require('../config/mongo/mySchema');

app.post('/person', function(req, res) {
    var Data = {
        name: req.body.name,
        email: req.body.email
    };

    var info = new Info(Data);

    info.save(function (error, data){
        if (error) {
            console.log(error);
        }
        else {
            console.log('done');
        }
    });
});

关于javascript - 如何在Node.JS中的模块中破坏代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27451846/

10-14 18:54
查看更多