【发布时间】:2020-02-02 10:25:01
【问题描述】:
所以,我和 Beau 一起在 this 教程中关注 freeCodeCamp YouTube 学习使用 MERN 堆栈构建一个简单的应用程序。然而,在使用 Postman 时,我在尝试向 localhost:5000/users/add 发送 POST 请求时收到此错误消息:
"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,然后选择raw 和JSON。我正在输入以下内容:
{
"username": "Andrew"
}
如果有人能帮我解决这个问题,将不胜感激。同样,这是我使用 MERN 堆栈的第一次体验,我真的很喜欢将 MongoDB 与 Express/React 一起使用的想法,所以我真的想不仅为这个项目解决这个问题,还为任何未来的项目解决这个问题。
我也读到过像我这样的例子缺少使用 bodyParser;然而,正如视频中提到的,这不再需要,而是我们可以简单地使用express,如app.use(express.json()); 所示。这是正确的吗?
谢谢。
【问题讨论】:
标签: node.js mongodb express http postman