mongodb开启auth,mongoose需要怎么连接?
发布于 7 年前 作者 linkenliu 4236 次浏览 来自 问答

现在目前的情况是控制台和用工具连接都没有问题,但是mongoose查询数据时就会报未授权的错误。

  • 代码如下:
const connect =  ()=> {mongoose.connect('mongodb://username:password@127.0.0.1:27017/database');};
connect();
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.on('disconnected', connect);
  • 然后试了这样子 还是不行
var options = {
    db: { native_parser: true },
    server: { poolSize: 5 },
    replset: { rs_name: 'userAdmin' },
    user: xxx
    pass: xxx
}
const connect =  ()=> {mongoose.connect('mongodb://xxx:xxx@127.0.0.1:27017/xxx',options)};
connect();
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.on('disconnected', connect);
var options = {
    db: { native_parser: true },
    server: { poolSize: 5 },
    replset: { rs_name: 'userAdmin' },
    user: xxx
    pass: xxx
}
const connect =  ()=> {mongoose.connect('mongodb://127.0.0.1:27017/xxx',options)};
connect();
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.on('disconnected', connect);

都不行,这个要怎么破?

2 回复

使用下面的试试: mongodb://XXX:XXXX@127.0.0.1:27017/yourdb?authSource=admin

@WindTrace 就可以了。感谢,磨蹭了好久。还得看看为什么要加个authSource=admin,文档连接的地方都没提到,还是我看的太不仔细了。

回到顶部