node.js - 如何使用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
}
}
我怎样才能使这项工作?
解决方案
你可以这样做:
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return collection.find({}).toArray()
//return collection.findOne({}) // Or like this, to just return one result
}
});
推荐阅读
- sql - 有条件地在插入前触发器中删除插入而不返回错误
- strapi - 我在响应中收到 Strapi 电子邮件 Api 错误:内部服务器错误
- javascript - Sinon - 如何使调用的函数间接返回某些内容
- kubernetes - Kubernetes,代码片段通过 go 客户端动态扩展/缩小 pod
- php - For循环缺少mysql DB PHP的第一行
- vb.net - 如何在 Visual Basic .NET 中支持自定义对象的上下文隐式转换?
- reactjs - 从 React 状态处理动态背景
- c# - 通过 StructureMap 定义“HttpClient”单例会导致有关“HttpMessageHandler”未在运行时配置的错误
- verilog - 如何在 Verilog 中构建向上计数器
- jenkins - Jenkins 脚本化管道仅在 Github 中发生提交时触发作业