首页 > 解决方案 > 如何使用hapi js返回mongodb查询结果

问题描述

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

我怎样才能使这项工作?

标签: node.jsmongodbapihapijs

解决方案


你可以这样做:

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

推荐阅读