嗨,有人可以解释一下我如何将 MongoDB 请求从构造函数导入到我的 Controller 吗?
要导出的类:
class getCampus {
constructor (){
data.collection('campuses').find({}).toArray(function (err, campus) {
if (err) {
res.send({ 'error': 'en error has occured'});
} else {
res.send(campus);
}
});
}
}
module.exports = getCampus;
我想导入到哪里
app.get('/campuses', (req, res) => {
// data.collection('campuses').find({}).toArray(function (err, campus) {
// if (err) {
// res.send({ 'error': 'en error has occured'});
// } else {
// res.send(campus);
// }
// });
});
最佳答案
如果你说:
,你应该能够做到这一点 // getCampus.js
class getCampus {
// ... your code
}
module.exports = getCampus;
然后像这样使用它:
const getCampus = require('getCampus'); // <-- Path and name of your file (you can ommit the .js)
app.get('/campuses', async function(req, res) {
const campus = await getCampus(); // Added async/await if getCampus is an asynchronous operation
res.send(campus);
}
但是,我建议将您的类命名为您的域,如下所示:
// Campus.js
class Campus {
constructor(var1, var2, etc) {
// define whatever is needed to build a campus
}
getCampus(id) {
// Now this is a getter to your campus
}
getCampuses() {
}
}
然后这样调用它:
const Campus = require('Campus');
const campusObj = new Campus;
const arrCampus = campusObj.getCampuses();
这样,你的代码会更干净,更容易维护。有很多方法可以做到这一点,我建议您看看 ES6 Classes .
关于node.js - NodeJS 类导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51710242/