node.js - NodeJS 类导入

标签 node.js mongodb

嗨,有人可以解释一下我如何将 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/

相关文章:

node.js - NodeJS, Mongoose : How to get related data using mongoose

javascript - Node.js:在模块范围内使用时, `this` 运算符的上下文是什么?

node.js - 尝试保存数据时,Express、Passport 和 sequelize 崩溃

node.js - Mongodb findOne 与或

javascript - 使用 mongodb 聚合框架计算频率

用于基于事务的事件的 Mongodb

mongodb - 带有嵌入式数据透视表的多对多

javascript - node.js ~ express req.on ('end' ) 触发但不触发 req.on ('data' )

javascript - 发送电子邮件时出现 SSL 错误,无法连接到 Postfix

javascript - NestJs 验证管道无法正常工作