How to use async/await with mongoose
Basically I want a similar snippet, but written with proper async/await syntax.
(async () => { try { await mongoose.connect(dbURI, dbOptions) } catch (err) { console.log('error: ' + err) }})()
Please try this, Below code has basics of db connectivity and a query :
const mongoose = require('mongoose');const Schema = mongoose.Schema;let url = 'mongodb://localhost:27017/test';const usersSchema = new Schema({ any: {}}, { strict: false});const Users = mongoose.model('users', usersSchema, 'users');/** We've created schema as in mongoose you need schemas for your collections to do operations on them */const dbConnect = async () => { let db = null; try { /** In real-time you'll split DB connection(into another file) away from DB calls */ await mongoose.connect(url, { useNewUrlParser: true }); // await on a step makes process to wait until it's done/ err'd out. db = mongoose.connection; let dbResp = await Users.find({}).lean(); /** Gets all documents out of users collection. Using .lean() to convert MongoDB documents to raw Js objects for accessing further. */ db.close(); // Needs to close connection, In general you don't close & re-create often. But needed for test scripts - You might use connection pooling in real-time. return dbResp; } catch (err) { (db) && db.close(); /** Needs to close connection - Only if mongoose.connect() is success & fails after it, as db connection is established by then. */ console.log('Error at dbConnect ::', err) throw err; }}dbConnect().then(res => console.log('Printing at callee ::', res)).catch(err => console.log('Err at Call ::', err));
As we're talking about async/await
then few things I wanted to mention - await
definitely needs it's function to be declared as async
- otherwise it would throw an error. And it's recommended to wrap async/await
code inside try/catch
block.
const connectDb = async () => { await mongoose.connect(dbUri, dbOptions).then( () => { console.info(`Connected to database`) }, error => { console.error(`Connection error: ${error.stack}`) process.exit(1) } )}connectDb().catch(error => console.error(error))
Lets assume the use of then()
is prohibited, you can result to this...
const connectDb = async () => { try { await mongoose.connect(dbConfig.url, dbConfigOptions) console.info(`Connected to database on Worker process: ${process.pid}`) } catch (error) { console.error(`Connection error: ${error.stack} on Worker process: ${process.pid}`) process.exit(1) }}