1

I've been trying to build APIs with Hapi, started with something simple as returning all users from database:

{
    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
    }
}

How can I make this work?

3
  • Are there any errors? Are you using the MongoDB node driver? Is the db connection successful and collection variable declared correctly (pointing to a valid collection)? Commented Nov 11, 2018 at 2:32
  • There's no error, the Console.log did show the expected result (an array of users) so I suppose the connection and query are good. Yes, I'm using MongoDB node drive const mongoClient = require('mongodb').MongoClient; Commented Nov 11, 2018 at 13:27
  • Possible duplicate of cursor.toArray() returns a promise instead of array Commented Nov 11, 2018 at 22:21

1 Answer 1

3

You could do :

server.route({
 method: 'GET',
 path: '/',
 handler: (request, h) => {        
   return collection.find({}).toArray()
  //return collection.findOne({}) // Or like this, to just return one result
 }
});
Sign up to request clarification or add additional context in comments.

1 Comment

indeed, this works like a charm and it's simpler than I thought.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.