如何使用hapi js返回mongodb查询结果

时间:2018-11-10 23:28:57

标签: node.js mongodb api hapijs

我一直在尝试使用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
    }
}

我该如何做?

1 个答案:

答案 0 :(得分:2)

您可以这样做:

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