CNode

mongodb开启auth,mongoose需要怎么连接?

问答
Llinkenliu发布于10 年前最后回复10 年前2 回复4876 浏览0 收藏

现在目前的情况是控制台和用工具连接都没有问题,但是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)

W
WindTrace#1·10 年前

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

L
linkenliu#2·10 年前

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

参与回复
登录后即可参与回复。登录