Unable to connect to MongoDB via node js - node.js

I am writing a Node JS script to connect to MongoDB via mongoose library. When i tried to connect to MongoDB server i am getting MongoServerSelectionError: getaddrinfo ENOTFOUND. I tried in github, stackoerlow and websites suggested by google. But, nothing helpful. I created clusters in mongodb and everything works fine and i whitelisted the IP using 0.0.0.0\0.
Thanks in advance..!!!

This is the code I usually use for mongo connection.
import mongoose from 'mongoose';
import { Db } from 'mongodb';
import config from '../config';
export default async (): Promise<Db> => {
const connection = await mongoose.connect(config.databaseURL, { useNewUrlParser: true, useCreateIndex: true });
return connection.connection.db;
};
where config.databaseURL is mongo url with username and password.
Please try using your mongo url in mongo compass. That url should work with this code.

Related

VPS not respond to request MongoDB-NodeJS

I bought a VPS server and installed Nodejs and Mongodb in it. Then I transferred my existing database file to mongodb, which I set up on VPS. I made the connection via NodeJS. The database seems to be working, but when I make a request, for example http://serverip:port/fetchData, I get the following error
'It looks like you are trying to access MongoDB over HTTP on the native driver port.'
could you please help me to solve this problem?
Here is NodeJs connection code
const URL = "mongodb://serverIp:port/dbname";
const connection = mongoose
.connect(URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
family:4
})
.then(() => console.log("Successfully Connected DB"))
.catch((e) => console.log("DB CONNECTION ERROR: "+e));
module.export = connection;
Note --> I added my desktop ip to access mongodb database and I can easily manage with my own desktop
HTTP interface for MongoDB Deprecated since version 3.2 :)
Check Mongo Docs: HTTP Status Interface

How do i resolve this Mongo Server Selection Error

Am quiet new to backend and database. I have a solution currently using mongodb. It was working fine till yesterday when i starting having the connect ETIMEDOUT 13.37.254.237:27017 error. Nothing was changed in the URI path or tampered with. It just started and i have not been able to sort it out.
is there any help available please?
I have created another cluster and its working well. But my initial cluster that has datas which are live from clients is not connecting still.
My connection code
I have used these connections code but it has not worked. It was connecting fine all through yesterday but today without tampering with the code, couldn't connect to my mongodb
mongoose.connect(process.env.MONGO_URI,{ useNewUrlParser: true, useUnifiedTopology: true });
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URL);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.log(error);
process.exit(1);
}
};
my mongoose connection and the timedout error
Whenever you connect to Mongodb using IPs that keep updating from your system causes this kind of issues.
also this can be due to your network connection. So i will advice you to:
To allow connection from any IP address(but must ensure your URI is not made known to the public to avoid attack/ access from unwanted users.)
2.Check your network status(data)
3. Run the mongo URI on your atlas

Cannot do raw queries on admin API doesn't work on MongoDB Atlas

My api server wrote with Node.js , database is MongoDB.
API works fine in my local.
When I push the same data to MongoDB Atlas and push my api server to Heroku
MongoDB version 4.2
Call the API I get the error
{"error":"cannot do raw queries on admin in atlas"}
API:
https://movie-with-atlas.herokuapp.com/api/getTwRanking
My API server code about connect to MongoDB Atlas:
const mongoose = require('mongoose');
if (process.env.NODE_ENV !== 'test') {
// MongoDB Atlas
mongoose.connect('mongodb+srv://myAccount:myPassword#cluster0.vcwmp.mongodb.net/movietogo?retryWrites=true&w=majority' , { useNewUrlParser: true });
// if connect with my local API is fine
// mongoose.connect('mongodb://localhost/movietogo');
}
I have checked my Network Access on MongoDB Atlas, set 0.0.0.0/0 (includes your current IP address) for Heroku, the issue still exists.
How do I fix my connect with MongoDB Atlas issue ? Thanks.
It comes from my API code:
I search the collection TwRanking and find the object key theater is TwRanking
getTwRanking (req, res, next) {
console.log('check getTwRanking');
const cityCollection = mongoose.model("TwRanking", MovieSchema, "TwRanking");
cityCollection.find({ "theater": "TwRanking" })
.then(movie => res.send(movie))
.catch(next);
},
I guess it catchs the error.
If look the answer MongoError: cannot do queries on admin in atlas
connect code change like this
mongoose.connect('mongodb://myAccount:myPassword#cluster0-shard-00-00.vcwmp.mongodb.net:27017,cluster0-shard-00-01.vcwmp.mongodb.net:27017,cluster0-shard-00-02.vcwmp.mongodb.net:27017/movietogo?ssl=true&replicaSet=cluster0-shard-0&authSource=admin');
I will get the error:
GET https://movie-with-atlas.herokuapp.com/api/getTwRanking 503 (Service Unavailable)

Use mongoose in an angular project

I try to integrate MongoDB in my project angular 6. I want to use the ODM Mongoose.
npm install mongoose --save
I created this service which must manage the connection with the database
import { Injectable } from '#angular/core';
import { mongoose } from 'mongoose';
#Injectable()
export class BD {
private bd;
public test: string;
constructor(mongoose: mongoose){}
Test(){
mongoose('the url of the database')
this.bd = mongoose.connection;
this.bd.on('error', console.error.bind(console, 'error: impossible connection to the database'));
this.bd.once('open', ()=>{console.log('connected to the DB :}')})
}
}
When I launch the application in my browser I have this erreur:
SCRIPT5009: 'global' is not defined
What does this error mean?
Is this how I have to import mongoose?
Thank you in advance for your help
Mongoose is a library designed specially for node.js and won't work in the browser environment. In order to be able to connect the db - you need to establish node.js back-end server, for example express.js. Then you will be able access your resources through the REST api.
Also, you cannot establish connection to the database directly, because you need somehow secure the data inside those database. When you connecting to the database directly - everyone who can take a look at your code will gain acess to the data and this is serious security problem.

Fail to connect Mongoose to Atlas

I'm always connecting to the "admin" DB, which is a fixed bug.
Using Mongoose 5.0.6 MongoDb 3.6 and trying to connect to Atlas.
My question, what driver Mongoose 5.0.6 depend on?
How can I find out when Mongoose will have that fix?
On a different direction, is there a way to connect with MongoDB then use this connection with
Mongoose?
Cheers
Basically you should try connecting with your url link, and specify the DB name on the mongoose connect method
so if your cluster link is:
mongodb+srv://userName:Passwrod#clustor.mongodb.net/
and your DB name is:
testDB
then you should call the mongoose.connect method as follows:
mongoose.connect('mongodb+srv://userName:Passwrod#cluster.mongodb.net/', {dbName: 'testDB'});
Connection is established when you use this connection string for (MongoShell 3.6+) :
var connDB = "mongodb+srv://<username>:<password>#cluster-fax0w.mongodb.net/test"
However, you will not be able to read/write data without entering the DBName in the mongoose.connect().
mongoose.connect(uri, { dbName: <your DB name> })
.then( () => {
console.log('Connection to the Atlas Cluster is successful!')
})
.catch( (err) => console.error(err));
Just a side note if you ever get an error connecting to the MongoDB Atlas make sure:
You've whitlisted our IP address / all (0.0.0.0/0)
Your credentials are right
Firewall / anti-virus are disabled
And if all fails
Make sure your DNS is a public one. Or maybe change it to Google's public DNS.
Throwing a link for the same:
https://www.youtube.com/watch?v=F9u5ULrRt3Y
Goodluck!

Resources