Mongodb Atlas Express.js Error: getaddrinfo ENOTFOUND - mongodb

I want to connect my express app to my mongoDb Atlas cluster.I'm from Iran, and cloud databases are sanctioned for us. I used VPN to bypass it in order to be able to practice.
Is there some coding mistake that I've done or is it because of using VPN?
The error:
(node:9008) 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.
connected
events.js:174
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
is listening...
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1448:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:17)
[nodemon] app crashed - waiting for file changes before starting...
And the code:
database.js
----------------
const mongoDb = require('mongodb');
const MongoClient = mongoDb.MongoClient;
let _db;
const mongoConnect = callback => {
MongoClient.connect(
'mongodb+srv://<someUser>:<somePassword>#<someCluster>-zh1eb.mongodb.net/test?retryWrites=true'
)
.then(client => {
console.log('\nconnected\n');
_db = client.db();
callback();
})
.catch(err => {
console.log('\nerror\n', err);
throw err;
});
};
const getDb = () => {
if (_db) {
return _db;
}
throw 'NO DATABASE FOUND';
};
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
app.js
------------
...
const mongoConnect = require('./util/database').mongoConnect;
...
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});

I found out what was the problem:
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});
should actually be
mongoConnect(() => {
app.listen(3000, () => { console.log('\nis listening...\n');});
});
Silly me... :)
For those having such issue:
first check out whether the source of problem is your code or the connection to MongoDb.
That is instead of choosing "connect your application" select "connect with Mongodb Compass".
If the Mongodb Compass could connect and show your cluster, then definitely there is something wrong with your code, esp. how it's coded to connect.

Related

MongoDB error when trying to connect to it

trying to get my code to connect to mongodb.
I have start mongo db compass, rund mongosh and mongod in cmd
add a new db to mongodb.
edit a new url to connect.
run npm start and get this and i dont connect to mongodb:
(node:14420) [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.
(Use `node --trace-warnings ...` to show where the warning was created)
my db.ts
import { MongoClient } from 'mongodb';
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'xxxxx';
// Create a new MongoClient
export async function initMongo() {
try {
const client = new MongoClient(url,{ useNewUrlParser: true });
await client.connect();
const db = client.db(dbName);
at the bottom of db
} catch (e) {
console.log('Cannot connect to MongoDB. Will retry in 10 seconds ...');
await new Promise<void>(resolve => {
setTimeout(() => resolve(), 10000);
});
console.log('Retrying...');
return await initMongo();
}
await client.connect
connect have a line right true.

mongodb connection db is undefined with mongoose

I am connecting using Mongoose using the following way
import { createConnection } from 'mongoose';
this.m_context = createConnection('mongodb://localhost/master')
But when I try to access this.m_context.db it is giving me undefined.
What am I doing wrong here? I checked the connection string that is working fine in the compass.
What I found is, createConnection doesn't open connection and because of that, it was giving undefined, as it gives connection DB info only if the connection is open.
this.m_context = await new Promise<Connection>((resolve) => {
createConnection('mongodb://localhost/master', undefined, (error, result) => {
resolve(result)
});
});

Mongoose Connection Error in Stackblitz - Mean app

I am trying to create a mean app. I am receiving errors while connecting mean app with MongoDb using mongoose. I am using "express": "^4.17.1", and "mongoose": "^6.0.7".
const mongoose = require('mongoose');
// Connecting to MongoDb
mongoose.connect(
'mongodb+srv://MongoDb:<password>#cluster0.xfdie.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDb');
});
mongoose.connection.on('error', (err) => {
if (err) {
console.log('Error in MongoDb Connection' + err);
}
});
It's working fine with the localhost but I am receiving the following error in Stackblitz.
Error in MongoDb ConnectionTypeError: this._handle[e] is not a function
(node:13) UnhandledPromiseRejectionWarning: TypeError: this._handle[e] is not a function
at Resolver.querySrv [as resolveSrv] (https://file-sharing-portal.jw.staticblitz.com/blitz.fa2fa735bbb029186c23972eb56445ed5c5fdef5.js:6:585119)
at Object.resolveSRVRecord (/home/projects/file-sharing-portal/node_modules/mongodb/lib/connection_string.js:55:9)
at Object.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/operations/connect.js:41:36)
at eval (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:127:23)
at Object.maybePromise (/home/projects/file-sharing-portal/node_modules/mongodb/lib/utils.js:518:5)
at MongoClient.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:126:24)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:785:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:776:19)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/index.js:328:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13) 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:13) [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.
Please assist.
I asked for help in stackblitz-help channel in discord for the same and was informed that Mongoose isn't supported yet : https://github.com/stackblitz/core/issues/251
const mongoose = require('mongoose');
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect("CONNECTION_STRING", "OPTIONS", (error) => {
if (error)
console.log("Connection error - ", error);
else
console.log("MongoDB connection established");
});
let server = http.createServer(app);
server.setTimeout(500000);
server.listen(3000);
try with above code snippets

Trying to update data to compass using mongoose but it shows error

I am a newbie and learning mongoose. I am trying to connect with local server and update data to mongoDB Compass but its' throwing error. I am not able to understand what mistake I am doing. Kindly help me to solve it.
db.on("connection", () => console.log("Connected Successfully"));
db.on("disconnect", () => console.log("Disconnected Successfully"));
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
firstEmployee.save(function (err, res) {
if (err) throw error;
console.log(res);
});
db.close();
});
and error is = throw er; // Unhandled 'error' event
^
ReferenceError: error is not defined

How to use Mongoose to connect mongo-atlas db?

I'm following this tutorial to setup the mongo atlas db.
https://developerhandbook.com/mongodb/connect-mongo-atlas-mongoose/
But on the setup of connection, I got error like
(node:60566) UnhandledPromiseRejectionWarning: MongoError: user is not allowed to do action [find] on [admin.sample_airbnb]
at queryCallback (/Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/cursor.js:223:25)
at /Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/connection/pool.js:541:18
at process._tickCallback (internal/process/next_tick.js:61:11)
(node:60566) 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:60566) [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 seems atlas db is using "admin" collection by default, how can I change it to "sample_airbnb" collection?
const connector = mongoose.connect(
'mongodb+srv://test:<password>#cluster0-ppeaz.mongodb.net/a?retryWrites=true&w=majority'
)
.then(() => {
// connector.useDb('sample_airbnb?');
const Listing = mongoose.model(
'listingsAndReviews',
new mongoose.Schema({
name: String,
summary: String,
}),
'sample_airbnb'
);
Listing.findOne({}).then((r) => {
console.log(r);
})
})
(node:60566) You need to add "admin permission"s to be able to query the db. This will be under "security" tab then "Database Access". "Add new user" button (which is then used in your connection string).
".mongodb.net/a?" needs to be ".mongodb.net/sample_airbnb?"
(node:60566) Use try catch e.g.
const connector = mongoose.connect(
'mongodb+srv://test:<password>#cluster0-ppeaz.mongodb.net/sample_airbnb?retryWrites=true&w=majority'
)
.then(() => {
// connector.useDb('sample_airbnb?');
const Listing = mongoose.model(
'listingsAndReviews',
new mongoose.Schema({
name: String,
summary: String,
}),
'sample_airbnb'
);
try {
const listings = await Listing.findOne({});
res.json(listings);
} catch (err) {
res.json({ message: err });
}
});
});