Node.js MongoError: у администратора нет прав на выполнение команды - PullRequest
0 голосов
/ 03 октября 2019

Здравствуйте, я пытался создать Custom Express API для связи с MongoDB, но когда я пытаюсь сделать почтовый запрос с помощью Почтальона, я получаю эту ошибку

{
  ok: 0,
  errmsg: 'not authorized on admin to execute command { insert: "users", documents: [[{_id ObjectIdHex("5d962346040f94390c75af87")} {email test@email.com} {password mypassword} {__v 0}]], ordered: true, writeConcern: { w: "majority" }, lsid: { id: {4 [103 212 165 139 101 156 64 219 134 229 99 101 244 58 241 13]} }, txnNumber: 1.000000, $clusterTime: { clusterTime: 6743616258408710147, signature: { hash: [182 133 122 147 115 29 40 38 207 106 105 195 60 131 107 121 63 161 82 165], keyId: 6718054837855977472.000000 } }, $db: "admin" }',
  code: 8000,
  codeName: 'AtlasError',
  name: 'MongoError',
  [Symbol(mongoErrorContextSymbol)]: {}
}

Вначале я думалэто было что-то, связанное с привилегиями пользователя в MongoDB Atlas, но я уже попробовал почти все из них. Вот как выглядит весь проект, и спасибо заранее:

index.js

require('./models/User');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const authRoutes = require('./routes/authRoutes');

const app = express();

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

const mongoUri = 'mongodb+srv://myusername:mypassword@cluster0-ekepr.mongodb.net/admin?retryWrites=true&w=majority';



mongoose.connect(mongoUri, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});

mongoose.connection.on('connected', () => {
    console.log('Connected to mongo instance')
});

mongoose.connection.on('error', (err) => {
    console.error('Error connecting to mongo', err)
});

app.get('/', (req, res) => {
    res.send('Hi there!');
});

app.listen(3000, () => {
    console.log('Listening on port 3000');
});

/src/models/User.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    }
});

mongoose.model('User', userSchema);

/ src / routs / authRoutes.js

const express = require('express');
const mongoose = require('mongoose');
const User = mongoose.model('User');


const router = express.Router();

router.post('/signup', async (req, res) => {
    // console.log(req.body);
    const { email, password } = req.body;

    try {
        const user = new User({ email, password });
        await user.save();
    } catch(err){
        console.error(err);
    }
    res.send('You made a post request');
});

module.exports = router;

А вот так выглядит необработанное тело моего запроса json

{
    "email": "test@email.com",
    "password": "mypassword"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...