How to use async/await with mongoose
Solution 1
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)
}
})()
Solution 2
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.
Solution 3
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)
}
}
xakepp35
I do love everything about PC; From power generation plants, electricity and transistors, to designing, developing, optimizing, testing and using complex software stacks. I love microcontrollers, CPUs, GPUs and crafting cases, racks, and even cooling systems for datacenter rooms. I love bios modding, asm, C, C++, Javascript, Golang. I wrote 16-bit programs in turbo pascal, back in school times, and saw Windows 3.11. I've played with visual basic, and used C-rootkits for winserver2003. I've met times of renaming Delphi 7 to Rad Studio. I knew Visual C++ 6.0. I built linux kernels and ramfs for embedded systems. I've smiled with Gentoo, laughed at X.Org, and used Freebsd ports, to build chromium and vlc on a slow LGA775 platform, thats infinite story.. Only thing I hate - is Apple: macbook, osx, iphon, stevjobs, et al.. These are worst things in the present universe and history of IT! Dont even mind to name it when children are nearby!!!
Updated on June 04, 2022Comments
-
xakepp35 almost 2 years
In node.js I had code like following:
mongoose.connect(dbURI, dbOptions) .then(() => { console.log("ok"); }, err => { console.log('error: '+ err) } );
Now i want to do it with async/await syntax. So i could start with
var mcResult = await mongoose.connect(dbURI, dbOptions);
, afaik it will wait for operation, until it ends with any result (much like calling C functionread()
orfread()
in syncronous mode).But what should I write then? What does that return to the
mcResult
variable and how to check for an error or success? Basically I want a similar snippet, but written with proper async/await syntax.Also I wonder because I have auto reconnect, among
dbOptions
:dbOptions: { autoReconnect: true, reconnectTries: 999999999, reconnectInterval: 3000 }
Would it "stuck" on
await
forever, in case if database connection is unavailble? I hope you can give me a clue on what would happen and how that would work.