我在 MongoDB Atlas 中创建了一个集群,但似乎无法向其中写入数据。
const uri = "mongodb+srv://myUser:myPass@myDB-4myav.mongodb.net/portfolio";
我将此作为我要连接的 uri,每次我尝试写入数据库时,都会收到此错误:
{ MongoError: not authorized on admin to execute command { insert: "users", documents: [[{name Daniel} {_id ObjectIdHex("5aa6d7d6396deb25844ccb52")} {__v 0}]], ordered: false }
我读到我需要创建一个具有“root”角色的管理员用户,但是当我使用 mongo shell 连接到我的数据库并尝试创建它时,我得到了这个:
Error: couldn't add user: not authorized on admin to execute command
所以基本上我没有可以写入我的数据库的用户。
我也曾尝试让用户在 MongoDB Atlas 网站(当然是我的集群)上拥有所有可能的角色,然后通过 mongo shell 连接它,但同样失败了。
总结一下:我在 MongoDB Atlas 上创建了一个新集群。如何向其中写入数据?
在此先感谢,如果我遗漏了一些简单而愚蠢的东西,请随时指出。
最佳答案
{ MongoError: not authorized on admin to execute command { insert: "users", documents: [[{name Daniel} {_id ObjectIdHex("5aa6d7d6396deb25844ccb52")} {__v 0}]], ordered: false }
此错误表明您的代码正在尝试将文档插入 admin
数据库,该数据库是为用户和角色信息保留的系统数据库。
在您的连接字符串中,您打算使用 portfolio
数据库。但是,srv
连接字符串格式不支持指定数据库,因此您的选项被忽略并使用了默认数据库 admin
。连接后您需要选择portfolio
数据库。
Mongoose 问题跟踪器 (GitHub issue #6106) 中也报告了这一点,其中一位用户发布了您可以采用的解决方法:
mongoose.connection.on('connected', function() {
// Hack the database back to the right one, because when using mongodb+srv as protocol.
if (mongoose.connection.client.s.url.startsWith('mongodb+srv')) {
mongoose.connection.db = mongoose.connection.client.db('portfolio');
}
console.log('Connection to MongoDB established.')
});
mongoose.connect(...);
I have read that I need to create an admin user with the role of "root" but when I connect to my database using the mongo shell and try creating it, I get this:
您需要manage users via MongoDB Atlas而不是 mongo
shell。您可以创建具有“读取和写入任何数据库”角色的用户帐户(或使用“高级选项”获得更精细的权限)。
关于mongodb - 使用 Mongoose 和 SRV 连接字符串将数据插入 MongoDB Atlas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49243587/