Search code examples
node.jsmongodbexpressazure-cosmosdb

Node.js - MongoDB - Asynch GET API How to Wait for Promise?


I'm new to Node.js and MongoDB but am trying to figure out how best to implement a GET endpoint in Node.js/MongoDB/Express

For some reason, and I think it's because my database is an Azure Cosmos MongoDB, the only way that I can make a connection is to use async since what I understand as a synchronous db connection attempt skips over any other code and the connection is never made.

So here is my code so far:

    const app = express();

    app.get('/jobs', async (req, res) => { 
    var url = "mongodb://****************"
    const  client = new  MongoClient(url);
    await client.connect();
    console.log("connected to database");<--This works!
    const database = client.db("jobinfoaccount");<-This is the name of my Azure DB Resource
    const query = {"jobrequests":"123"}
    //jobrequests is the name of the collection in jobinfoaccount 
    var collection = database.collection("jobrequests").find().toArray(function (err,results) {
      console.log(results);
      res.json("Loaded" + results)
    })
  });

The problem that I am currently having us that the execution is blowing right by this line:

    var collection = database.collection("jobrequests").find().toArray (function (err,results) 

And the execution doesn't even hit these lines:

      console.log(results);
      res.json("Loaded" + results)

When I look at the watch statement in VSCode, it says there's a promise there, but I am not sure how to handle this:

enter image description here

And when I call the endpoint in Postman, it just spins:

enter image description here

UPDATE When I try using await as shown here:

var collection =  await database.collection("jobrequests").find().toArray (function (err,results) {

I still don't see it hitting the next line 70 going straight to line 73: enter image description here

But collection seems to have resolved the promise:

enter image description here

Now I am wondering if there something wrong with one of these lines of code, in particular jobinfoaccount and jobrequests

const database = client.db("jobinfoaccount");
var collection =  await database.collection("jobrequests").find().toArray (function (err,results) {

This is my Resource Name in Azure: enter image description here

And this is the Collection Name:

enter image description here

Thanks in advance..


Solution

  • Trying to figure out how best to implement a GET endpoint in Node.js/MongoDB/Express.

    Below are the steps I tried to implement a GET endpoint in Node.js/MongoDB/Express:

    • The code I attempted creates a single MongoDB connection on server startup and then reuses it for each request. It avoids repeatedly creating and closing connections for every request.

    • Consistent use of async/await makes the code more understandable and handles asynchronous tasks in a better manner.

    • It is easier to debug and comprehend the data being retrieved by using the console.log(results) statement to record the retrieved data to the console before delivering it as a response.

    • I attempted some code that uses try/catch to catch and handle any errors that arise when working with the database.

    • The code below transmits the received data as a JSON response (res.json(results)), making it simple for client side to manipulate the data.

    • For better code structure and readability, the route definition and MongoDB connection setup are separated in the code below.

    Code I tried with:

    const express = require('express');
    const { MongoClient } = require('mongodb');
    
    const app = express();
    const port = 3000; 
    const url = '****'; 
    
    app.use(express.json());
    const client = new MongoClient(url);
    
    async function connectToDatabase() {
      try {
        await client.connect();
        console.log('Connected to MongoDB');
      } catch (error) {
        console.error('Error connecting to MongoDB:', error);
      }
    }
    connectToDatabase();
    
    // Retrieve all data from the database
    app.get('/jobs', async (req, res) => {
      try {
            const database = client.db('newDb');
            const collection = database.collection('newColl'); 
    
            const results = await collection.find().toArray();
            console.log(results); 
            res.json(results);
      } catch (error) {
            console.error('Error:', error);
            res.status(500).json({ error: 'An error occurred' });
      }
    });
    
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });
    

    Output: In Console:

    Server is running on port 3000
    Connected to MongoDB
    [
      {
        _id: new ObjectId("64f57a8e93de8d013cb645af"),
        id: '1',
        title: 'Job 1',
        description: 'This is the first job',
        location: 'New York'
      },
      {
        _id: new ObjectId("64f57ab993de8d013cb645b0"),
        id: '2',
        title: 'Job 2',
        description: 'This is the second job',
        location: 'Los Angeles'
      }
    ]
    

    In Server: localhost:3000/jobs

    [
        {
            "_id": "64f57a8e93de8d013cb645af",
            "id": "1",
            "title": "Job 1",
            "description": "This is the first job",
            "location": "New York"
        },
        {
            "_id": "64f57ab993de8d013cb645b0",
            "id": "2",
            "title": "Job 2",
            "description": "This is the second job",
            "location": "Los Angeles"
        }
    ]