【问题标题】:Using a module for my DB, I am not retrieving my data为我的数据库使用一个模块,我没有检索我的数据
【发布时间】:2017-03-06 15:00:42
【问题描述】:

抱歉,如果标题描述性不强。

我正在使用 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;
  }
 });
}

我已经采用与其他“导出”方法相同的方式,例如“插入”,因此我确信这个问题与我的数据库连接或导出“配置”无关。

【问题讨论】:

  • 很抱歉我不能使用标签 node。我需要更高的声誉:'(

标签: javascript node.js cloudant


【解决方案1】:

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

有很多方法可以解决这个问题(还有很多很多关于 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);
    });
});

【讨论】:

  • 我需要的。非常感谢!
  • 很高兴为您提供帮助 ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多