Deprecated body-parser? - node.js

I am getting the error message deprecated body-parser i've looked up other methods concerning parsing the data but none seem to work. the below code what ive got
const express = require('express');
const app = express();
const Task = require('./api/models/ListModels.js'); //created model loading here
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const routes = require('./api/routes/ListRoutes.js'); //importing route
routes(app); //register the route
app.listen(3000, () => {
console.log('running on 3000')
})
The error:
PS C:\Users\demar\Desktop\New folder\ListAPI> node app.js
(node:10424) 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.
running on 3000
(node:10424) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\topologies\server.js:562:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\connection\pool.js:316:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\connection\connection.js:245:50)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:10424) 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(). (rejection id: 1)
(node:10424) [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.

It honestly tells you what to do..
To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
I added the options and it works perfectly..
Originally:
// Connect to Mongo:
mongoose.connect(db).then(() => console.log("Mongo DB Connected")).catch(err => console.log(err));
Current:
// Connect to Mongo:
mongoose.connect(db, { useNewUrlParser: true}).then(() => console.log("Mongo DB Connected")).catch(err => console.log(err));
This fixed the issue

The error is that your version of Node's URL string parser, that Mongoose is using, is deprecated.
Pass in the option {useNewUrlParser: true} to mongoose.connect() to use the new Node Core URL API.
mongoose.connect('mongodb://localhost/Tododb', {useNewUrlParser: true})

That error is appearing because you didn't specified the port number mongodb is running on.
mongoose.connect('mongodb://localhost:27017/databasename', { useNewUrlParser: true })
this will fix your issue :)

Yes, body-parser has been deprecated.
Don't use it anymore
Since Express 4.16+ the body parsing functionality has become built into express
You can do
app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads
From directly express, without having to install body-parser.
so you can uninstall body-parser using npm uninstall body-parser, and simply use the above code from express.

Related

MongoNetworkError: failed to connect to server [ac-99ygtmu-shard-00-02.lm1wpuv.mongodb.net:27017]

I'm new to nodeJS, I'm currently following a tutorial on youtube. I have set up my connection string:
const mongoose = require("mongoose");
const connectionString =
"mongodb+srv://mikeyxx:ntpassword#nodeexpressprojects.lm1wpuv.mongodb.net/?retryWrites=true&w=majority";
mongoose
.connect(connectionString)
.then(() => console.log("CONNECTED TO THE DB..."))
.catch((err) => console.log(`Got an error: ${err}`));
But when I lunch my node app. I get this error:
(node:25416) 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.
(Use `node --trace-deprecation ...` to show where the warning was created)
server is listening on port: 5000...
(node:25416) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.
(node:25416) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology:
true } to the MongoClient constructor.
Got an error: MongoNetworkError: failed to connect to server [ac-99ygtmu-shard-00-02.lm1wpuv.mongodb.net:27017] on first connect [MongoNetworkTimeoutError: connection timed out
at connectionFailureError (C:\Users\USER\Desktop\Backend\node-express-course\03-task-manager\starter\node_modules\mongodb\lib\core\connection\connect.js:362:14)
at TLSSocket.<anonymous> (C:\Users\USER\Desktop\Backend\node-express-course\03-task-manager\starter\node_modules\mongodb\lib\core\connection\connect.js:330:16)
at Object.onceWrapper (node:events:627:28)
at TLSSocket.emit (node:events:513:28)
at Socket._onTimeout (node:net:562:8)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)]
When I run npm start, I expected to get: CONNECTED TO THE DB... but instead I get an error

Getting Timeout error while connecting MongoDB Atlas with Mongoose

I am trying to connect to my database on MongoDB Atlas using mongoose. But every time it's giving me the following error:
(node:2327) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT cluster0-abjwg.gcp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:206:19)
(node:2327) 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:2327) [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.
I have tried whitelisting the IP. Also, the same code is working fine on another machine but not on my machine.
The code is:
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
// Connecting to MongoDB
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log('Connection established');
})
app.use(express.json());
app.listen(port, () => {
console.log(`Here we go on port: ${port}`);
});
It is supposed to give output:
Here we go on port: 5000
Connection established
But I'm getting the only the first output and the error.
DNS resolution for TXT records appears to be broken on your machine. You can use the legacy URI (the one without srv) to connect instead.
My Internet Service Provider was blocking the connection. I changed my DNS to Google's Public DNS and the error was no more. I followed the link below to change my DNS.
https://developers.google.com/speed/public-dns/docs/using

trouble connecting to mongodb

I am following a tutorial and trying to connect to mongodb, i have two files
the first is server.js with the following codes
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//DB config
const db = require('./config/keys').mongoURI;
//connect to mongo
mongoose
.connect(db,{ useNewUrlParser: true })
.then(()=>console.log('Connected to mongodb...'))
.catch(err=>console.log(err));
const port = process.env.PORT || 5000;
app.listen(port,()=>console.log(`server connected on port ${port}`));
The second is the config file
module.exports = {
mongoURI:'mongodb+srv://denis:password#shoppingapp-wmnbw.mongodb.net/shopping?retryWrites=true&w=majority'
}
what I am trying to achieve is to show on the console connected to mongodb...
instead I am given this error message
server connected on port 5000
(node:35030) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [shoppingapp-shard-00-01-wmnbw.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to shoppingapp-shard-00-01-wmnbw.mongodb.net:27017 closed
at TLSSocket.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connection.js:372:9)
at Object.onceWrapper (events.js:417:26)
at TLSSocket.emit (events.js:310:20)
at net.js:672:12
at TCP.done (_tls_wrap.js:557:7)]
at Pool.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:310:20)
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/pool.js:561:14
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/pool.js:1008:9
at callback (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:97:5)
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:124:7
at _callback (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:349:5)
at Connection.errorHandler (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:365:5)
at Object.onceWrapper (events.js:417:26)
at Connection.emit (events.js:310:20)
at TLSSocket.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connection.js:370:12)
at Object.onceWrapper (events.js:417:26)
at TLSSocket.emit (events.js:310:20)
at net.js:672:12
at TCP.done (_tls_wrap.js:557:7)
I have tried to change the driver version but still get the errors, where am I going wrong?
It turns out I was not connecting with the right IP address.

trying to connect to mongodb Atlas using nodeJs

I am working on a small project(REST API) using nodeJs + MongoDB. I have been able to install MongoDB locally and connect to it using mongoose. However for some reason, when I try to connect using MongoDB Atlas it fails. It looks like it connects but then after 2 seconds, I get an error message saying sockets closed(see error below). I have no clue what is going on. I have whitelisted my IP, checked my login info to make sure I am using the correct password and indeed I am using because I am able to connect using MongoDB compass. Any help is greatly appreciated.
My current local ENV package versions are:
nodeJs:V9.7.1
mongoose:V6.1
=== MongoDb Atlas ===
mongodb:3.6
Below is the code that I am using to connect to the database:
var express = require('express'),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
user = require('./api/models/userModel'),
config = require('./api/config');
bodyParser = require('body-parser');
var authRoutes = require('./api/routes/authRoutes'),
userRoutes = require('./api/routes/userRoutes'),
reviewRoutes = require('./api/routes/reviewRoutes');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://user:myPass#cluster0-shard-00-00 zd6jq.mongodb.net/myDb');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Swagger Info
var options = {
explorer : true
};
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
//END Swagger Info
//REGISTER ROUTES
userRoutes(app);
authRoutes(app);
reviewRoutes(app);
app.listen(port);
console.log('iReview RESTful API server listenning on port: ' + port);
module.exports = app;
====ERROR MESSAGE ===
/Users/mdiez/node_test/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
MongoError: server cluster0-shard-00-00-zd6jq.mongodb.net:27017 sockets closed
at Pool.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/topologies/server.js:325:47)
at Object.onceWrapper (events.js:219:13)
at Pool.emit (events.js:127:13)
at Connection.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/pool.js:101:12)
at Object.onceWrapper (events.js:219:13)
at Connection.emit (events.js:127:13)
at Socket.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/connection.js:142:12)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at TCP._handle.close [as _onclose] (net.js:558:12)
var uri = 'mongodb://<usernamr>:<password>#<clustername>/<dbname>?ssl=true&replicaSet=<replica setname>&authSource=admin';
var db = mongoose.connect(uri).catch((error) => { console.log(error); });
Specify the replica set name, ssl true and authentication database. This is based on reference from Atlas documentation.
You can use this code to connect to Compass and Application. You just need to the following:
replace all the three primary and secondary shard from Cluster -> Overview
replace natours-app with your cluster name.
Compass:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?authSource=admin&replicaSet=natours-app1-shard-0&readPreference=primary&appname=MongoDB%20Compass&retryWrites=true&ssl=true
Application:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?ssl=true&replicaSet=natours-app-shard-0&authSource=admin&retryWrites=true

mongoose atlas connection fails while mongodb driver works

I need to connect to an Atlas replica set with mongoose. It's really weird. If I connect via the mongodb-js driver everything works fine. CRUD works like a charm.
Here's how I connect via MongoClient:
let dbURL = 'myAtlasConnectionURL';
let db = await MongoClient.connect(dbURL);
await db.collection('users').insert({name: 'username'});
let result = await db.collection('users').find({});
log.info('result', await result.toArray());
db.collection('users').remove({});
await db.close();
But if use the mongoose connection I keep getting:
MongoError: connection 5 to cluster0-shard-00-02-c4nst.mongodb.net:27017 closed
at Function.MongoError.create (/mypath/vendors/node_modules/mongodb-core/lib/error.js:29:11)
at Socket.<anonymous> (/mypath/vendors/node_modules/mongodb-core/lib/connection/connection.js:202:22)
at Object.onceWrapper (events.js:316:30)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at TCP._handle.close [as _onclose] (net.js:548:12)
Here's how I try to connect via mongoose, using the same dbURL as above:
mongoose.connect(dbURL, {
useMongoClient: true
});
I have no idea, what could possibly be wrong.

Resources