Ошибка UnhandledPromiseRejectionWarning при попытке запустить мой Node.js приложение

#node.js #mongodb #mongoose

#node.js #mongodb #мангуст

Вопрос:

Мой код:

 const fastify = require('fastify');
const mongoose = require('mongoose');

const app = fastify();

try {
    mongoose.connect('mongodb://localhost:27017/notes_db');
} catch (e) {
    console.error(e);
}

app.get('/', (request, reply) => {
    try{
        reply.send("Olá mundo");
    } catch(e) {
        console.error(e);
    }
})

app.listen(5000, (err, address) => {
    if (err) {
        console.error(err);
        process.exit(1);
    }
    console.log(`Server running on ${address}`);
});
 

Когда я запускаю команду npm start или node index.js мне отображается эта ошибка:

 (node:10332) 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.
Server running on http://127.0.0.1:5000
(node:10332) UnhandledPromiseRejectionWarning: Error: Password contains an illegal unescaped character
    at parseConnectionString (C:UsersmikaeDesktopnotes-servernode_modulesmongodbliburl_parser.js:299:13)
    at parseHandler (C:UsersmikaeDesktopnotes-servernode_modulesmongodbliburl_parser.js:130:14)
    at QueryReqWrap.callback (C:UsersmikaeDesktopnotes-servernode_modulesmongodbliburl_parser.js:114:7)
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:205:10)
(node:10332) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10332) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the 
future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
 

Мой сервер запущен, но я хочу знать, как исправить это сообщение.

Ответ №1:

Можете ли вы попробовать указать useNewUrlParser параметр следующим образом:

 try {
    mongoose.connect('mongodb://localhost:27017/notes_db', { useNewUrlParser: true });
} catch (e) {
    console.error(e);
}
 

Редактировать

Поскольку вы пытаетесь подключиться к кластеру MongoDB Atlas, а не к локальной установке, замените URI подключения на тот, который вы получаете в Atlas.

Вот учебное пособие, которое я нашел: https://medium.com/@sergio13prez/connecting-to-mongodb-atlas-d1381f184369

Комментарии:

1. Не сработало, та же ошибка произошла снова (node:12844) 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. Server running on http://127.0.0.1:5000 (node:12844) UnhandledPromiseRejectionWarning: Error: Password contains an illegal unescaped character at parseConnectionString (C:UsersmikaeDesktopnotes-servernode_modulesmongodbliburl_parser.js:299:13) at parseHandler (C:UsersmikaeDesktopnotes-servernode_modules...

2. Вы уверены, что используете тот же код, который показываете? Потому что изменение избавило бы, по крайней мере, от предупреждения. Кроме того, поскольку у вас есть a trycatch вокруг части подключения, это не приведет к UnhandledPromiseRejectionWarning

3. Да, вот оно prnt.sc/wwpgkj и мой код prnt.sc/wwpkgs

4. На этот раз ошибка другая, на скриншоте. У вас есть mongodb, работающий локально?

5. Я пытаюсь запустить MongoDB Atlas, но я не знаю, как я могу подключить кластер в моем файле index.js . Я читаю этот учебник medium.com/swlh / … Итак, я использую тот же mongoose connect, что и в этом уроке