使用nodeJS连接到mongoDB时出现问题

hfyxw5xn  于 2023-01-16  发布在  Node.js
关注(0)|答案(1)|浏览(264)

我在ubuntu服务器上托管了一个Mongo数据库。我创建了一个admin用户以便能够连接Nodejs来创建数据库,添加表格等。我可以连接 * mongoDB compass* 没有问题,但是从nodeJS mongo返回一个错误。
连接功能:

const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
//connect to db
mongoose
    .connect("mongodb://" + process.env.DB_USER_PASS + "@2.56.247.250:27017/?authMechanism=DEFAULT")
    .then(() => console.log('Connecté a la base de donné'))
    .catch((err) => console.log("Erreur de connexion :", err));

下面是错误:

Erreur de connexion : MongoServerError: Authentication failed.
    at Connection.onMessage (C:\Users\arnau\Desktop\messIO\node_modules\mongodb\lib\cmap\connection.js:230:30)
    at MessageStream.<anonymous> (C:\Users\arnau\Desktop\messIO\node_modules\mongodb\lib\cmap\connection.js:61:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (C:\Users\arnau\Desktop\messIO\node_modules\mongodb\lib\cmap\message_stream.js:125:16)
    at MessageStream._write (C:\Users\arnau\Desktop\messIO\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at Writable.write (node:internal/streams/writable:337:10)
    at Socket.ondata (node:internal/streams/readable:766:22)
    at Socket.emit (node:events:513:28) {
  ok: 0,
  code: 18,
  codeName: 'AuthenticationFailed',
  connectionGeneration: 0,
  [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
ecbunoof

ecbunoof1#

错误AuthenticationFailed表示连接字符串有问题,驱动程序无法连接到该字符串。请在此处查看所有详细信息:https://www.mongodb.com/docs/manual/reference/connection-string/
潜在问题:
1.* * 特殊字符**:来自文档:If the username or password includes the following characters: / ? # [ ] @ those characters must be converted using percent encoding.
1.* * username:password format检查环境变量的格式是否正确,username和pass之间是否有:,并且没有空格。
1.* * 检查您的授权数据库
:创建用户时,使用命令use dbname在默认值("admin"数据库是默认值)或特定数据库上创建。如果在特定数据库上创建,则可能需要在连接字符串上添加auth数据库名称。
您可以尝试以上所有解决方案,使用mongosh命令建立连接,以验证连接字符串是否正常。

相关问题