Mongoose in Node.js using await/async"/>
How to connect MongoDB using Mongoose in Node.js using await/async
const express = require("express")
const app = express();
const mongoose=require("mongoose")
async () =>
{
try {
let res=await mongoose.connect(uri)
console.log("Succesfully logged")
} catch (error) {
console.log("Error",error)
}
app.get("/", (req, res) =>{
//stuff
}
我试过了,但是我的异步函数没有被调用,我如何让服务器等待并先执行异步函数。我想检查数据库是否已连接。但代码只是跳过它。
编辑:
const verification= async () =>
{
try {
let res=await mongoose.connect(uri)
console.log("Succesfully logged")
} catch (error) {
console.log("Error",error)
}
}
const Itemx=new mongoose.Schema
{
Item:String
}
const Items= mongoose.model('Item',Itemx)
//Items.
verification()
所以,我尝试了这个,它有效,但问题是如果我决定稍后关闭连接,它是同步完成的,我试图避免,我不能在验证时使用等待,因为它在异步函数之外。
回答如下:要确保在服务器开始监听之前调用async函数,需要使用await关键字等待函数完成。
const express = require("express")
const app = express();
const mongoose=require("mongoose")
const verification = async () => {
try {
await mongoose.connect(uri);
console.log("Successfully connected to the database");
} catch (error) {
console.log("Error",error)
}
};
verification().then(() => {
app.get("/", (req, res) => {
// stuff
});
app.listen(3000, () => console.log("Server is running"));
});
这段代码中,用await调用了校验函数,保证在连接数据库之前服务器不会开始监听。连接数据库后,将执行 then 块,将服务器设置为侦听端口 3000。
更多推荐
How to connect MongoDB using Mongoose in Node.js using await/async
发布评论