因此,在this教程中,我将与Beau一起在freeCodeCamp YouTube上学习如何使用MERN Stack构建简单的应用程序。但是,在使用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;
我已经按照本教程进行了学习,甚至将我的代码与已完成的仓库中的代码进行了比较,但我无法确定有什么不同,因此我不确定如何解决此错误。
同样是邮递员,我选择POST
,然后输入localhost:5000/users/add
,然后选择Body
,然后选择raw
和JSON
。我输入以下内容:
{
"username": "Andrew"
}
如果有人可以帮助我解决此问题,将不胜感激。再说一次,这是我第一次使用MERN堆栈,我真的很喜欢将MongoDB与Express / React一起使用的想法,所以我真的想不仅为这个项目,而且为将来的项目解决这个问题。
我还读到像我这样的例子缺少使用bodyParser。但是,正如视频中所提到的,不再需要它了,取而代之的是我们可以使用express
,如app.use(express.json());
所示。这是正确的吗?
谢谢。
答案 0 :(得分:0)
开始工作!我从以下位置更改了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?
,一切正常!