Express.js - Mongo对象返回Undefined

时间:2014-12-15 12:24:45

标签: json node.js mongodb express

我正在尝试使用Express.js从Mongodb获取JSON,并返回" Undefined"在我的控制台中。你能建议吗?

app.js:

var db = monk('localhost:27017/nodetest1', {
  username : 'USERNAME',
  password : 'PASSWORD'
});

index.js:

router.get('/url', function(req,res){

    var db = req.db;
    var collection = db.get('test1');

    collection.find({},{},function(e,docs){
    console.log(docs) // Returns "Undefined"
    res.send(docs);
    });
});

1 个答案:

答案 0 :(得分:3)

检查" e"对象,可能你有错误

router.get('/url', function(req,res){
  var db = req.db;
  var collection = db.get('test1');

  collection.find({},{},function(e,docs){
    if (!e) {
      console.log(docs); // Data you supposed to get in a correct way
    } else {
      console.log(e); // Checking the error - connection failure, bad authentication, etc.
    }
  });
});