我用命令
创建了mongodb用户use admin
db.createUser(
{
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
}
)
然后在我的应用程序中,我试图连接像这样的猫鼬
var options = {
user: "superuser",
pass: "12345678"
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';
mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
通过mongoose
插入数据时出现此错误MongoError: not authorized for insert on twitter-mongo.users
请告诉我我的代码有什么问题
答案 0 :(得分:10)
您必须在连接字符串中声明authSource参数,以指定包含您的用户凭据的数据库的名称:
var options = {
user: "superuser",
pass: "12345678",
useMongoClient: true
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo?authSource=admin';
请注意,我还设置了" useMongoClient"为真。这使使用MongoClient.connect验证身份验证和 open()已弃用错误消息。
答案 1 :(得分:6)
这很好用:
var options = { server: { socketOptions: { keepAlive: 1 } } };
var connectionString = 'mongodb://admin:admin1234@localhost:27017/myDB';
mongoose.connect(connectionString, options);
//Add those events to get more info about mongoose connection:
// Connected handler
mongoose.connection.on('connected', function (err) {
console.log("Connected to DB using chain: " + connectionString);
});
// Error handler
mongoose.connection.on('error', function (err) {
console.log(err);
});
// Reconnect when closed
mongoose.connection.on('disconnected', function () {
self.connectToDatabase();
});
答案 2 :(得分:1)
我确实使用docker运行了mongo服务,然后使用此代码将mongoose连接到了它
mongoose.connect('mongodb://user:pass@localhost:port/MyDB?authSource=admin', {
useNewUrlParser: true
})
.then(() => console.log('Connected to MongoDB ...'))
.catch(err => console.error('Could not connect to MongoDB:', err));
这等于
mongo --username user --password pass --authenticationDatabase admin --port 27017
在连接后,然后使用MyDB
数据库对其执行查找,聚合,插入等操作
答案 3 :(得分:0)
尝试
const mongooseConnectionString = 'mongodb://superuser:12345678@ localhost/twitter-mongo?authSource=admin'
答案 4 :(得分:0)
您需要在要操作的数据库中创建用户,而不是在管理DB中创建用户。
使用此命令,
use twitter-mongo;
db.createUser({
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
});
相反,
use twitter-mongo
db.createUser({
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
});
答案 5 :(得分:0)
mongoose.createConnection('mongodb://username:password@35.238.xxx.xxx:27017/dashboards?authSource=admin', {
useNewUrlParser: true
}, (e) => {
if (e) throw console.error('Error connecting to mongo database master');
console.log('Connected to mongo database master.');
});
答案 6 :(得分:0)
创建连接字符串的正确方法是 var connection = mongoose.createConnection("mongodb://username:pwd@hostip:port/dbname?authSource=admin", options);
请使用 authSource=admin 在连接字符串中进行身份验证。