skip to Main Content
let mongodb = require('mongodb').MongoClient;
    let express = require("express")
    let app = express()
    let connectionString = 'mongodb://ToDoAppUser:[email protected]:27017,ac-u9kgapm-shard-00-01.8rdkdoi.mongodb.net:27017,ac-u9kgapm-shard-00-02.8rdkdoi.mongodb.net:27017/?ssl=true&replicaSet=atlas-68qno6-shard-0&authSource=admin&retryWrites=true&w=majority'
    let db 
    mongodb.connect(connectionString,function(err,client){
     
      if (err) throw err
       db = client.db()
       app.listen(3000)
       console.log("Database connected.");
    
    })
    
    app.use(express.urlencoded({extended : false}))

Trying to retrieve data from MongodB

As you can see that , I am trying to retrieve data from MongoDB collection named #item and want to print it. But it shows an empty array. I am stuck on this. kindly help me to resolve this issue.

    app.get("/", function(req, res){
      **// this collectio method of mongodb returns empty array.
      // however, mongodb got connected, but i cannot retreive data from mongodb**  
      db.collection('items').find().toArray(function(err, items) {
        if(err) console.log(err)
        console.log(items)
    
      })

2

Answers


  1. You need to use the following format.

    async function findOneListingByName(client, nameOfListing) {
        const result = await client.db("sample_airbnb").collection("listingsAndReviews").findOne({ name: nameOfListing });
    
        if (result) {
            console.log(`Found a listing in the collection with the name '${nameOfListing}':`);
            console.log(result);
        } else {
            console.log(`No listings found with the name '${nameOfListing}'`);
        }
    }
    

    This code above is worked for me.
    By the way, you can read their documentation here for more examples:
    https://www.mongodb.com/developer/languages/javascript/node-crud-tutorial/

    Login or Signup to reply.
  2. My guess is that the call to fetch items from DB is asynchronous, and you’re trying to use items synchronous manner.

    Try adding async to the controller function and using await for the DB request. Like this:

    app.get("/", async function(req, res){
            /*  Mongo documents don't show any parameters for the toArray method
             * Read here https://www.mongodb.com/docs/manual/reference/method/cursor.toArray/#mongodb-method-cursor.toArray
             *
            */
           const itemsFromDB = await db.collection('items').find().toArray()
           conssole.log('items are:' itemsFromDB )
    
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search