【问题标题】:How to return mongodb query result with hapi js如何使用hapi js返回mongodb查询结果
【发布时间】:2019-04-14 03:03:31
【问题描述】:

我一直在尝试使用 Hapi 构建 API,从简单的事情开始,例如从数据库中返回所有用户:

{
    method: 'GET',
    path: '/users',
    handler: (request, h) => {
        var users;
        collection.find({}).toArray((err, users) => {      
            console.log(res)
            // I want to return the list of users here
            // return users // this one does not work
            // return h.response(users) // does not work either
        });

        return "" // or here
    }
}

我怎样才能做到这一点?

【问题讨论】:

  • 有错误吗?您使用的是 MongoDB 节点驱动程序吗? db 连接是否成功且collection 变量声明正确(指向有效集合)?
  • 没有错误,Console.log 确实显示了预期的结果(用户数组),所以我想连接和查询都很好。是的,我正在使用 MongoDB 节点驱动器const mongoClient = require('mongodb').MongoClient;

标签: node.js mongodb api hapijs


【解决方案1】:

你可以这样做:

server.route({
 method: 'GET',
 path: '/',
 handler: (request, h) => {        
   return collection.find({}).toArray()
  //return collection.findOne({}) // Or like this, to just return one result
 }
});

【讨论】:

  • 确实,这就像一个魅力,它比我想象的要简单。
猜你喜欢
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 2020-06-20
相关资源
最近更新 更多