如果尝试添加架构,我可以使用StringURI,但连接到MongoDB,我会收到错误消息:
MongoDB Connected ..
{ MongoError: not authorized on admin to execute command { insert: "animals", documents: [[{isEndangered true} {dateOfEntry 2019-10-03 22:33:54.852 +0000 UTC} {_id ObjectIdHex("5d967752e762ed56dc4f1dba")} {name Red Panda} {__v 0}]], ordered: true, writeConcern: { w: "majority" }, lsid: { id: {4 [194 242 186 89 84 47 69 212 143 253 85 42 86 82 70 95]} }, txnNumber: 1.000000, $clusterTime: { clusterTime: 6743708686104920070, signature: { hash: [247 92 77 50
194 115 41 36 114 64 156 130 20 135 223 112 71 207 137 248], keyId: 6728180188896559104.000000 } }, $db: "admin" }
at Connection.<anonymous> (C:\Users\xxxx\Documents\04_Programmering\mongoDB_Node\node_modules\mongodb\lib\core\connection\pool.js:466:61)
at Connection.emit (events.js:197:13)
at processMessage (C:\Users\xxxx\Documents\04_Programmering\mongoDB_Node\node_modules\mongodb\lib\core\connection\connection.js:364:10)
at TLSSocket.<anonymous> (C:\Users\xxxx\Documents\04_Programmering\mongoDB_Node\node_modules\mongodb\lib\core\connection\connection.js:533:15)
at TLSSocket.emit (events.js:197:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:150:17)
ok: 0,
errmsg:
'not authorized on admin to execute command { insert: "animals", documents: [[{isEndangered true} {dateOfEntry 2019-10-03 22:33:54.852 +0000 UTC} {_id ObjectIdHex("5d967752e762ed56dc4f1dba")} {name Red Panda} {__v 0}]], ordered: true, writeConcern: { w: "majority" }, lsid: { id: {4 [194 242 186 89 84 47 69 212 143 253 85 42 86 82 70 95]} }, txnNumber: 1.000000, $clusterTime: { clusterTime: 6743708686104920070, signature: { hash: [247 92 77 50 194 115 41 36 114 64 156 130 20 135 223 112 71 207 137 248], keyId: 6728180188896559104.000000 } }, $db: "admin" }',
code: 8000,
codeName: 'AtlasError',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {} }
我的连接字符串:(使用软件包“ config”,没有问题[尝试])
{
"mongoURI": "mongodb+srv://xxxx:xxxx@xxxx-xxxx.mongodb.net/admin?retryWrites=true&w=majority"
}
具有Mongoose驱动程序和连接:
mongoose
.connect(db, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true})
.then(() => console.log('MongoDB Connected ..'))
.catch(err => console.log(err));
我已经尝试过:
const newAnimal = new Animal({
name: 'Red Panda',
isEndangered: true
});
newAnimal
.save()
.then(item => console.log(item))
.catch(err => console.log(err));
这是新事物,我甚至不想在开始之前就退出。免费的Atlas帐户对于较小的演示和学习来说似乎是一个好的开始,而不必处理连接和模式等更多的事情。
答案 0 :(得分:2)
错误提示:
MongoError: not authorized on admin to execute command { insert: ....
这意味着您正在尝试插入admin
数据库,这是一个受限制的特殊数据库。
更改您的连接字符串以使用另一个数据库,例如:
"mongodb+srv://xxxx:xxxx@xxxx-xxxx.mongodb.net/test?retryWrites=true&w=majority"
,以便您连接到名为test
的数据库。您的插入内容应该可以使用。