简体   繁体   English

Mongoose.connect() 在连接字符串中指定数据库时失败

[英]Mongoose.connect() fails when database is specified in connection string

I'm running a local MongoDB server and am trying to connect to it from a node.js server using the Mongoose library.我正在运行本地 MongoDB 服务器,并尝试使用 Mongoose 库从 node.js 服务器连接到它。

I'm using SCRAM-SHA-1 as the authentication mechanism我使用 SCRAM-SHA-1 作为身份验证机制

I'm able to connect to it with the admin account when I don't specify a database to connect to, using a connection string such as:当我没有指定要连接的数据库时,我可以使用管理员帐户连接到它,使用连接字符串,例如:

mongodb://{username}:{password}@{address}:{port}?authMechanism=SCRAM-SHA-256

But when I try to specify which database to connect to, using a connection string such as:但是当我尝试指定要连接到哪个数据库时,使用连接字符串,例如:

mongodb://{username}:{password}@{address}:{port}/database123?authMechanism=SCRAM-SHA-256

the authentication fails.认证失败。

For reference, my code looks like:作为参考,我的代码如下所示:

    const mongoose = require('mongoose');

    let conn_string = `mongodb://mongo_uname:mongo_pass@192.168.1.1:3000/database123?authMechanism=SCRAM-SHA-256`

    mongoose
    .connect(database_uri, {
        useUnifiedTopology: true
    })
    .then(() => console.log('MongoDB database Connected...'))
    .catch((err) => console.log(err))

Is there a different way to specify which database to connect to with mongoose, or is there something I can do differently when constructing the connection string to make it work?是否有不同的方法来指定使用 mongoose 连接到哪个数据库,或者在构造连接字符串以使其工作时我可以做一些不同的事情?

Cheers.干杯。

Make sure that the database user you are using is configured to read and write to the database uou are trying to connect to.确保您正在使用的数据库用户配置为读取和写入您尝试连接的数据库。

import mongoose from "mongoose";

const mongoDB = "mongodb://localhost:27017/twlight";
mongoose.Promise = global.Promise;

mongoose.connect(mongoDB, { useNewUrlParser: true })
.then(() => {
  console.log("Database is connected");
},
(err) => {
console.log("There is problem while connecting database " + err);
});

Please try请试试

Note: twilight is database name注意:twilight 是数据库名称

If you are using Mongoose v6+, you should NOT specify useUnifiedTopology .如果您使用的是 Mongoose v6+,则不应指定useUnifiedTopology

That is deprecated and if you include it, Mongoose will throw the error.这已被弃用,如果包含它,Mongoose 将抛出错误。 Try to include the connection string only:尝试仅包含连接字符串:

mongoose.connect(database_uri)

My error ended up being in the configuration of the database user I was trying to connect with, they weren't even set up to read or write to the database I was attempting to connect to.我的错误最终出现在我尝试连接的数据库用户的配置中,他们甚至没有设置为读取或写入我尝试连接的数据库。

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

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