mongodb Mongoose 无法连接-但控制台没有错误

y4ekin9u  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(159)

我正在尝试将我的app.js连接到MongoDB。上次成功了。这次,在这个新项目中,它无法连接。我没有收到控制台日志。也没有收到错误日志。代码中有什么问题吗?或者是MongoDB的问题。我三次检查了用户名和密码。

.env-File:

PORT = 8080
MONGO_DB_CLIENT = "mongodb+srv://Admin:<mypassword>@g5-cluster0.vthttto.mongodb.net/?retryWrites=true&w=majority"

字符串

app.js

require('dotenv').config();
console.log(process.env.MONGO_DB_CLIENT);

const express = require('express');
const app = express();
const port = process.env.PORT;
const mongoose = require('mongoose');
const cors = require('cors');

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

const connectString = process.env.MONGO_DB_CLIENT;
app.use(async(req,res,next) => {
   try {
       await mongoose.connect(connectString,{
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    console.log("Connected to MongoDB");
    next();

    } catch (error) {
        console.error(error);
    }
});

package.json依赖

"dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "mongoose": "^7.6.3"
  },

  • 我反复检查了用户名和密码
  • 安装了mongo数据库,没有帮助。所以我又删除了它。(我有mongoose)
  • 我登录:
console.log(process.env.MONGO_DB_CLIENT);


这样就行了

更新-我试过:

async function connectToMongoDB() {
  try {
    console.log(process.env.MONGO_DB_CLIENT);
    await mongoose.connect(process.env.MONGO_DB_CLIENT, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('Connected to the DB ✅');
  } catch (error) {
    console.log(error);
  }
}

connectToMongoDB();

这是控制台说的:

[1] MongoServerError: bad auth : authentication failed 
[1]     at MessageStream.<anonymous>
[1]   ok: 0,
[1]   code: 8000,
[1]   codeName: 'AtlasError',
[1]   connectionGeneration: 0,
[1]   [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }


.所以它必须是一个mongoDB身份验证问题,那么我猜..:/

tyky79it

tyky79it1#

try {
  console.log(process.env.MONGO_DB_CLIENT)
  await mongoose.connect(process.env.MONGO_DB_CLIENT);
  console.log( 'Connected to the DB ✅');
} catch (error) {
  console.log(error);
}

字符串
直接在主文件上尝试此操作并检查控制台

相关问题