首页 > 解决方案 > 错误:MongoError:管理员未授权执行命令

问题描述

因此,我将在教程中与 Beau 一起学习 freeCodeCamp YouTube 学习使用 MERN 堆栈构建一个简单的应用程序。但是,在使用 Postman 时,我在尝试向以下位置发送 POST 请求时收到此错误消息localhost:5000/users/add

"Error: MongoError: not authorized on admin to execute command { insert: \"users\", documents: [[{_id ObjectIdHex(\"5d96cd3f31092833b8253260\")} {username Andrew} {createdAt 2019-10-04 04:40:31.321 +0000 UTC} {updatedAt 2019-10-04 04:40:31.321 +0000 UTC} {__v 0}]], ordered: true, writeConcern: { w: \"majority\" }, lsid: { id: {4 [40 157 203 39 59 227 66 72 188 54 104 29 179 241 37 148]} }, txnNumber: 2.000000, $clusterTime: { clusterTime: 6743803110960922625, signature: { hash: [61 192 72 112 135 6 249 47 34 239 28 238 196 104 30 46 4 217 216 107], keyId: 6741907548619669504.000000 } }, $db: \"admin\" }"

在过去的几个小时里,我一直在网上查看多个 SO Q+A 线程,但我似乎找不到解决这个问题的方法。我看到一个常见的建议是在 MongoDB Atlas 中为我的用户提供 root 访问权限,但我不确定我会在哪里实现它。我也在使用所有免费选项,并且我已经读过,因为我正在使用这些选项,所以不能绕过这个错误?

这是我为此项目创建的用户的当前访问权限: 在此处输入图像描述

在网络访问下,我选择了自己的 IP 地址(使用任何地址都没有帮助)。

这是我们的server.js文件的代码:

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uri = "mongodb+srv://<username>:<password>@cluster0-idjjd.gcp.mongodb.net/admin?retryWrites=true&w=majority"; 
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once('open', () => {
  console.log('MongoDB database connection established successfully!');
});

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

app.listen(port, () => {
  console.log(`The server is running on port ${port}`);
});

我当然在uri变量中更改了自己的用户名和密码,只是不想在这里输入。

当我运行时nodemon server.js,我在终端中看到:

[nodemon] restarting due to changes...
[nodemon] starting node server.js
The server is running on port 5000
MongoDB database connection established successfully!

这是我们的user.model.js文件的代码:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema ({
  username: {
    type: String,     
    required: true,   
    unique: true,     
    trim: true,       
    minlength: 3      
  },
}, {
  timestamps: true
})

const User = mongoose.model('User', userSchema);

module.exports = User;

这是用于路由的users.js文件的代码:

const router = require('express').Router();
let User = require('../models/user.model');

router.route('/').get((request, response) => {
  User.find() 
    .then(users => response.json(users))
    .catch(error => response.status(400).json(`Error: ${error}`))
});

router.route('/add').post((request, response) => {
  const username = request.body.username;
  const newUser = new User({ username });

  newUser.save()
    .then(() => response.json('User added!'))
    .catch(error => response.status(400).json(`Error: ${error}`))
});

module.exports = router;

我已经按照教程进行了操作,甚至将我的代码与完成的 repo 的代码进行了比较,但我无法找出任何区别,所以我不确定如何解决这个错误。

再次在 Postman 中,我选择POST,然后输入localhost:5000/users/add,然后选择Body,然后选择rawand JSON。我正在输入以下内容:

{
    "username": "Andrew"
}

如果有人可以帮助我解决这个问题,将不胜感激。同样,这是我第一次使用 MERN 堆栈,我真的很喜欢将 MongoDB 与 Express/React 一起使用的想法,所以我真的想不仅为这个项目解决这个问题,还为任何未来的项目解决这个问题。

我还读到像我这样的例子缺少使用 bodyParser;但是,正如视频中所提到的,这不再需要,而是我们可以简单地使用express,如app.use(express.json());. 这个对吗?

谢谢你。

标签: node.jsmongodbexpresshttppostman

解决方案


让它工作!我将 uri 键更改为:

const uri = "mongodb+srv://<username>:<password>@cluster0-idjjd.gcp.mongodb.net/admin?retryWrites=true&w=majority";

const uri = "mongodb+srv://<username>:<password>@cluster0-idjjd.gcp.mongodb.net/test?retryWrites=true&w=majority";

刚刚换掉了这个位mongodb.net/admin?mongodb.net/test?一切正常!


推荐阅读