簡體   English   中英

如何在Node.JS中的模塊中破壞代碼?

[英]How to break code in modules in Node.JS?

我的以下代碼需要在兩個文件中使用:

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');
        }
    });
});

當你做

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

然后mySchema 變成什么module.exports是。 由於它是一個函數(針對您的情況),因此您只需簡單地調用它:

mySchema();

順便說一句:我不知道為什么將它定義為一個函數。 可能不是最好的主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM