无法连接到mongodb?

5f0d552i  于 2022-12-18  发布在  Go
关注(0)|答案(2)|浏览(220)

这同样的代码是完美的工作的一天,现在它不工作...
看起来这和访问控制有关,但我想不通。
我在StackOverflow上发现了类似的问题,但是,我不确定在何处实现db.createUser代码
下面是一个类似的StackOverflow问题:MongoDB - admin user not authorized
下面是我的代码

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
(node:7206) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:7206) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.
(node:7206) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Connected to database!
/Users/juan/StudioProjects/a-n-e-m-project/node_modules/mongodb/lib/core/connection/pool.js:453
          return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc));
                                                            ^

MongoError: (Unauthorized) not authorized on admin to execute command { find: "posts", filter: {  }, projection: {  }, lsid: { id: {4 [159 148 249 216 42 112 71 195 180 178 144 58 57 47 151 207]} }, $clusterTime: { clusterTime: {1671116335 2}, signature: { hash: {0 [201 157 29 0 111 232 144 103 241 214 206 247 184 152 135 214 250 188 25 170]}, keyId: 7127068168341684224.000000 } }, $db: "admin" }
    at Connection.<anonymous> (/Users/juan/StudioProjects/a-n-e-m-project/node_modules/mongodb/lib/core/connection/pool.js:453:61)
    at Connection.emit (node:events:513:28)
    at processMessage (/Users/juan/StudioProjects/a-n-e-m-project/node_modules/mongodb/lib/core/connection/connection.js:456:10)
    at TLSSocket.<anonymous> (/Users/juan/StudioProjects/a-n-e-m-project/node_modules/mongodb/lib/core/connection/connection.js:625:15)
    at TLSSocket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10)
    at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23) {
  ok: 0,
  code: 8000,
  codeName: 'AtlasError'
}
[nodemon] app crashed - waiting for file changes before starting...

这是服务器端代码所在的位置,以及所有的代码::
https://github.com/casas1010/mean-project/blob/main/backend/app.js
我有管理员权限,MongoDB应该允许从任何IP访问
下面是建立连接的代码::

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const postsRoutes = require("./routes/posts");

const app = express();

mongoose
  .connect(
    "mongodb+srv://USERNAME:PASSWORD@cluster0.fzb0uz9.mongodb.net/?retryWrites=true&w=majority"
  )
  .then(() => {
    console.log("Connected to database!");
  })
  .catch(() => {
    console.log("Connection failed!");
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

app.use("/api/posts", postsRoutes);

module.exports = app;
cu6pst1q

cu6pst1q1#

问题是你在mongodb atlas中没有授权用户,检查你是否有授权用户在那个数据库中使用,你需要访问的数据库是否有授权。看看从mongosh访问一个新用户来访问那个数据库,或者看看用户名或密码是否正确。我希望它能为你服务,如果出错我会查看更多信息;)
编辑:您需要更改用户“admin”才能访问此数据库

db.createUser({ user: "blogUser", pwd: "blogUserPwd", roles: [{ role: "dbAdmin", db: "blog" }, { role: "readWrite", db: "blog" } ]})
dy1byipe

dy1byipe2#

我最终降级了 Mongoose 版本,效果很好

相关问题