在Node.js API中显示整个MongoDB内容

时间:2017-02-28 17:07:26

标签: node.js mongodb

首先,不要担心,这是一个很小的数据集 - 我意识到通过API将整个生产数据库转储到单个屏幕上是不明智的...我只需要获得一个JSON转储整个(小)DB通过Node.js应用程序中的API端点返回。

我的应用程序使用以下代码成功返回单个记录:

MongoClient.connect("mongodb://localhost:27017/search", function (err, db) {

    if(err) throw err;

    db.collection('results', function(err, collection) {
        // search for match that "begins with" searchterm
        collection.findOne({'string':new RegExp('^' + searchterm, 'i')}, function(err, items){
            // get result
            var result;
            if (items == null || items.result == null){
                result = "";
            }
            else {
                result = items.result;
            }
            // return result
            res.send(result);
        });
    });
});

所以我知道Node正在成功地与Mongo交谈,但是如何调整这个查询/代码以基本上返回在MongoDB命令行上执行以下操作时得到的内容:

$ db.results.find()

3 个答案:

答案 0 :(得分:2)

这是片段。

model.find({}).exec(function (err, result) {
        if (err) {console.error(err); return;}
        else return result;
    });

首先使用预定义的模型并调用find。逻辑是放置一个空对象{}基本上渲染。从这个模型中选择所有。

有意义吗?

答案 1 :(得分:1)

正如你所描述的那样。

collection.find({}).exec((err, result) => {
  if (err) {
    console.log(err);
    return;
  }
  if (result.length > 0) {
  // We check that the length is > 0 because using .find() will always
  // return an array, even an empty one. So just checking if it exists
  // will yield a false positive
  res.send(result);
  // Could also just use `return result;`
});

答案 2 :(得分:0)

谢谢大家,在使用{}作为查询方面,我感谢您的答案指向了正确的方向。这是最终为我工作的代码:

db.collection('results', function(err, collection) {
    collection.find({}).toArray(function(err, docs) {
        res.send(docs);
    });
});

关键元素是 toArray(...)部分。