简体   繁体   English

为什么“服务器已连接”出现在快速应用程序中 VScode 终端中的“数据库已连接”之前?

[英]Why "Server is Connected" comes before the "Database is connected" in terminal of VScode in express app?

I just want to know Why "Server is Connected" comes before the "Database is connected" in terminal of VScode in express app?我只想知道为什么“服务器已连接”出现在快速应用程序中VScode终端的“数据库已连接”之前?

Here is my code这是我的代码

const express = require("express"); 
const cors = require("cors"); 
const mongoose = require("mongoose"); 
const exercises = require("./routes/exercises"); 
const users = require("./routes/users"); 

require('dotenv').config(); 
const app = express(); 


const port =  process.env.PORT || 8000; 

app.use(cors()); 
app.use(express.json()); 


mongoose.connect("mongodb+srv://@cluster0.lzvul.mongodb.net/my_database?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true");
  const db = mongoose.connection;
  db.on("error", console.error.bind(console, "connection error: "));
  db.once("open", () => {
    console.log("Connected successfully");
  });
  
app.listen(port , () => { 
    console.log(`Server is running on localhost:${port}`); 
})

First, take care of your credentials, use the.env file just like you used it for storing the port.首先,照顾好您的凭据,使用 .env 文件,就像使用它来存储端口一样。

Now, talking about what happened to your code.现在,谈谈你的代码发生了什么。 The mongoose.connection function returns a Promise , which means, a peace of code that will run along side the rest of your code if you don't specify that you want to wait for it to respond back. The mongoose.connection function returns a Promise , which means, a peace of code that will run along side the rest of your code if you don't specify that you want to wait for it to respond back. For this reason, the server starts running before the database is properly connected, it takes longer for your application to get in contact with mongodb servers than it takes for express to get running.出于这个原因,服务器在数据库正确连接之前开始运行,您的应用程序与 mongodb 服务器取得联系的时间比 express 运行所需的时间要长。

I strongly recommend you to have a look at the Promise documentation to understand it deeper.我强烈建议您查看Promise 文档以更深入地了解它。

Anyway a possible solution for know is to await for the mongoose connection to be stablished and just then start your server无论如何,一个可能的解决方案是等待 mongoose 连接建立,然后启动您的服务器

...
/* 
Assuming you've put your mongodb URI in the MONGO_URI variable 
at the .env file
*/
mongoose.connect(process.env.MONGO_URI)
  .then(() => {
    const db = mongoose.connection;
    db.on("error", console.error.bind(console, "connection error: "));
    db.once("open", () => {
      console.log("Connected successfully");
    });
  
    app.listen(port , () => { 
      console.log(`Server is running on localhost:${port}`); 
    });
  })
  .catch((err) => {
    console.log("Something went wrong with the database connection");
  });

By using the .then method we are basically saying, we want to wait for this function to respond, and when it responds we want to execute this following function, where we call the rest of logic you wrote, server startup included.通过使用.then方法我们基本上是说,我们要等待这个function响应,当它响应时我们要执行function,我们调用Z65E8800B5C6800AAD896F88的逻辑服务器。

That will make sure that the database initializes before the server and if something goes wrong with this process the server doesn't start.这将确保数据库在服务器之前初始化,如果此过程出现问题,服务器不会启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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