How to connect MongoDB using Mongoose in Node.js using await/async

编程入门 行业动态 更新时间:2024-10-05 03:24:29

How to connect MongoDB using <a href=https://www.elefans.com/category/jswz/34/1771443.html style=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

本文发布于:2024-05-30 05:38:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770184.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Mongoose   MongoDB   connect   Node   async

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!