I am new to nodejs and mongo db. I connected my code to mongodb compass it is getting connected too but just cannot find the database. Please help me This is my main file First.js
const express=require('express');
const app=express();
const parser=require("body-parser");
const mongoconnect=require("./util/database").mongoConnect;
const path=require("path");
const input=require("./routes/input");
app.use(parser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,"css")));
app.set('view engine','ejs');
app.set('views','views');
app.use((req,res,next)=>{
console.log("Hahah")
next();})
app.use(input);
mongoconnect(()=>{
app.listen(1234);
});
This is my database.js
const mongodb = require('mongodb');
let db;
const MongoClient= mongodb.MongoClient;
const mongoConnect=callback=>{
MongoClient.connect("mongodb+srv://jack:<password>@cluster0.xpkmi.mongodb.net/shop?retryWrites=true&w=majority").then(result=>{
console.log("connected")
db=result.db('shop');
callback();
}).catch(err=>{console.log(err)});
}
const getDb=()=>{
if(db)
{
return db;
}
throw 'No database found';
}
exports.mongoConnect=mongoConnect;
exports.getDb=getDb;
And in output when I run it shows me No database found
Ok, let's get clear with this. You declare a variable db (as undefined) in database.js. The mongoConnect function is asynchronous. So, what happens is, other synchronous functions and instructions are executed and db variable is still undefined. So, it throws error. After that, the db variable is set via your asynchronous call
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.