我的以下代码需要在两个文件中使用:
var Schema = mongoose.Schema;
var InfoSchema = new Schema ({
name: String,
email: String,
});
var Info = mongoose.model('Info', InfoSchema);
我需要在 listTerminal.js 中使用 Info 变量,并且需要在 paths.js 中使用 InfoSchema 。
我是 Node.js 新手,但仍然对 module.exports 感到困惑。谁能给我一盏灯吗?
我试图这样做:
module.exports = function() {
var Schema = mongoose.Schema;
var InfoSchema = new Schema ({
name: String,
email: String,
});
};
他们像这样调用我的routes.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/