为我的数据库使用一个模块,我没有检索我的数据

Using a module for my DB, I am not retrieving my data

抱歉,如果标题不是很清楚。

我正在使用 Node 并尝试使用 export.module 来获得干净的代码。

app.js

// ...
require('./router')(app);
module.exports = app;

router.js

cloudant = require("./helpers/cloudant")
// ...
module.exports = (app) => {
// ...
 app.post("/statsPage", function(req, res) {
 // ... 
  var a = cloudant.listUsers();
  console.log("from post ", a) // --> it shows ("undefined")
  if(a == false || a == undefined ) {
    res.render("error");
  } else {
    res.render("statsPage", {
      results: a
  });
}

cloudant.js

exports = module.exports = {}

exports.listUsers = function() {
 db.find({selector: {_id:{ "$gt": 0}}}, function(err, body) {
  if(err) {
   console.log(err);
   return false;
  } else {
   console.log(body.docs) // --> it shows results correctly
   return body.docs;
  }
 });
}

我已经用同样的方式制作了其他 "export" 方法,例如 "insert",所以我确信这个问题与我的数据库连接或导出都无关 "config" .

db.find方法是异步的,所以你从数据库中获取的数据只能在回调函数中使用。如果仔细查看在 cloudant.js 中导出的函数,您会发现没有 return 语句 returning 任何数据,仅在回调函数中没有帮不上什么忙

有很多方法可以解决这个问题(还有很多很多关于 SO 的帖子)。

最简单的解决方案是将您自己的回调传递给 listUsers 函数:

exports.listUsers = function (callback) {
    db.find({ selector: { _id: { "$gt": 0 } } }, function (err, body) {
        if (err) {
            console.log(err);
            callback(err);
        } else {
            callback(body.docs);
        }
    });
}

router.js

app.post("/statsPage", function(req, res) {
    cloudant.listUsers(function (a) {
        console.log("from post ", a);
    });
});