Node API MongoDB Query - How can I return the mongoDB query to the client?

Being new to JS I decided to throw my self into the deep end with some Node API development. I am experimenting with querying my mongoDB.

I currently have an index.js script for the API using the 'express' module. For a GET request I want to return the query results in an array/json as a response. I am importing the mongoDB query from another script I made called db_functions.js.

I have tried messing with the functions, trying to add return statements or something just to be get the query function I wrote to return an array. I have probably spent too much time on this issue already and its probably something simple that I didn't do.

I have a GET request looking like the following:

app.get('/db_query', function (req, res) {

    var result = db_functions.return_query();
    res.send(result)
});

I have experimented with some code I found at w3schools here: https://www.w3schools.com/nodejs/nodejs_mongodb_query.asp

It displays the result in the console but I want to return the result in an array to the client response.

const  db_url = "mongodb://localhost:27017/";
const  client = MongoClient(db_url, { useNewUrlParser:  true, useUnifiedTopology:  true })

  
function  return_query() {
    client.connect(function(err, db) {
        if (err) throw  err;
        var  db_var = db.db("test_db");
        db_var.collection("simple_data").find({}).toArray(function(err, result) {
            if (err) throw  err;
            console.log(result);
            db.close()
        });
    });
};

I want the client response to look like the one in the console.log shown below:

[
    {
    "_id": "6015c1c74fb541419e145db1",
    "name": "George",
    "phone": "00011333"
    },
    {
    "_id": "6015c1c74fb541419e145db2",
    "name": "John",
    "phone": "9911999"
    }
]

What am I missing here?

Upvotes: 0

Views: 790

Answers (2)

lasse
lasse

Reputation: 105

You need to return the query response using a callback function:

function  return_query(my_callback) {
    client.connect(function(err, db) {
        if (err) throw  err;
        var  db_var = db.db("test_db");
        db_var.collection("simple_data").find({}).toArray(function(err, result) {
            if (err) throw  err;
            console.log(result);
            my_callback(result)
            db.close()
        });
    });
};

and in your express server file:

app.get('/db_query', function (req, res) {

    db_functions.return_query(function(result) {
      res.send(result)
    });
    
});

Explanation

The query to your mongo database is asynchronous, which means the result is not coming back immediatly.

There are actually already two callback functions nested in your return_query function. One for the connection to the database and then, inside that, another one for retrieving the query response. This is why you can not simply return the response using the return keyword. The return keyword is bound to the closest (callback) function scope it is in.

If you get the (understandable) feeling that these callbacks get complicated quickly I recommend having a look at promises and async functions. They make working with asynchronous code in javascript and nodejs much easier.

Upvotes: 1

devMob
devMob

Reputation: 60

Are you trying to show the results with a get service and show it to client when they request it?

Because your code is running at the start and now its time to write a rest api service and send the result to client.

Upvotes: 0

Related Questions