Varun
Varun

Reputation: 5

mongodb express node throwing "client not defined" error

const express = require("express");
const app=express();
const port=8900;
const mongo =require("mongodb");
const MongoClient=mongo.MongoClient; //acess to function necessary to perform CRUD operations
const MongoUrl="mongodb://127.0.0.1:27017"
let db;
app.use(cors())



MongoClient.connect(MongoUrl, (error,connected)=>{
    if(error) console.log(error);
    db =client.db("EIS");
    app.listen(port,(error)=>{
        if (error) throw (error);
        console.log(`Server is running on ${port}`)
    })
})


app.get("/cuisine",(req,res)=>{
    db.collection("cuisine").find().toArray((error,result)=>{
        if(error) throw err;
        res.send(result);
    })
})

This code when run is sending an error saying client not defined. Can someone please help me understand why is it throwing "client not defined" error. This code is basically fetching the "cuisine" data from mongodb database which is accessible when viewing it separately. Also just to mention when running this code yes the mongo client is running.

Upvotes: 0

Views: 29

Answers (1)

Montgomery Watts
Montgomery Watts

Reputation: 4034

client on this line: db =client.db("EIS"); is not defined.

In the callback function of MongoClient.connect, the second argument is the client, which in your code you named connected. Either change the name of the argument from connected to client, or change client to connected on the line mentioned above.

Upvotes: 1

Related Questions