简体   繁体   中英

Connecting Node js to Mongo Atlas via Promise

Hey guys i am new to asynchronous programming so i studied well Promises and implemented a little bit but so far now i am facing an issue In order to connect my Mongo Atlas to Node js i found a code which was written as

App.js

const mongoconnect=require('./utils/database')
mongoconnect((client)=>{
console.log(client)
app.listen(3000)
})

utils/database.js

const mongodb=require('mongodb');
const Mongoclient=mongodb.MongoClient

const mongoconnect=(callback)=>{
Mongoclient.connect('mongodb+srv://ratnabh2615:ratnabh2614@cluster0- 
altfm.mongodb.net/test?retryWrites=true&w=majority')
.then(client=>{
    console.log('Connected')
    callback(client)
})
.catch(err=>console.log(err))
}

module.exports=mongoconnect

So as you can see in utils/database.js we are using a callback funcion but i want to use only Promise here so i tried to implement myself but failed as i am not so experienced with it.Could you please solve the issue ?

I did something like this, dont know how much wrong it is

utils/database.js

const mongodb=require('mongodb');
const Mongoclient=mongodb.MongoClient

const mongoconnect=()=>{
return new Promise((resolve,reject)=>{
    const url='mongodb+srv://ratnabh2615:ratnabh2614@cluster0- 
altfm.mongodb.net/test?retryWrites=true&w=majority';
    Mongoclient.connect(url).then(client=>{
        console.log('Connected')
        return resolve(client)
    }).catch(err=>console.log(err))
})
}
module.exports=mongoconnect

App.js

const mongoconnect=require('./utils/database')
mongoconnect.then(results=>{
console.log(results)
app.listen(3000)
}).catch(err=>console.log(err))

But i receive the error

mongoconnect.then(results=>{
         ^
TypeError: mongoconnect.then is not a function

Just call it like a function:

const mongoconnect=require('./utils/database');
mongoconnect().then(results=>{
  console.log(results);
}).catch(err=>console.log(err));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM