I'm trying to use mongoDB for my app.
I have 2 databases and use next code to connect:
var express = require("express");
var router = express.Router();
var mongojs = require("mongojs");
//var mongo_db =
//mongojs("mongodb://xxxxx:xxxxx#some_adress/cat_mean_db", ["tasks"]);
var mongo_db = mongojs("mongodb://xxxxx:xxxxx#localhost:3000/cat_db",
["tasks"]);
//get all docs(pages)
router.get("/tasks", function (req, res, next ) {
mongo_db.tasks.find(function (error, tasks) {
if(error)
res.send(error);
res.json(tasks);
});
});
if I use this db
var mongo_db =
mongojs("mongodb://xxxxx:xxxxx#some_adress/cat_mean_db",
["tasks"]);
everything is working well, but when I try to use db on localhost I got an exeption: connection 0 to localhost:3000 closed
the local db is exist and has user for shure.
From mongoose documentation on NPM :
Note: If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.
You should try using 127.0.0.1 instead of localhost.
Related
I am trying to connect to mongodb server locally at this ip mongodb://127.0.0.1:27017/ yet still no connection to the mongodb server
I have tried using localhost instead of 127.0.0.1 but not change .
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://127.0.0.1:27017/';
const dbname = 'conFusion';
console.log("before connect");
MongoClient.connect(url, (err, client) => {
console.log('Connected SuccessFully');
});
I have also run this command Mongod --dbpath=data --bind-ip 127.0.0.1:27017 but no change
Occasionally I would get the timeout error
My nodejs app can't connect to MondoDB Server.
I have already allowed all ip addresses (0.0.0.0/0) to connect.
const mongoose = require('mongoose');
const URL = '' //database url
mongoose.connect(URL, {useNewUrlParser: true}).then(db => {
console.log("Connected")
}).catch(err => {
console.log(err)
})
Above code throws "MongooseServerSelectionError: connection timed out" error
U have to provide URL in mongoose something like this
const url = 'mongodb://localhost:27017/myapp'
But before that please verify whether the mongo is running in your system or not.
Although I am not the first on Stackoverflow not to be able to connect to mongoDB atlas using mongoose, no one seems to have my specific error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-00-shqnc.mongodb.net:27017] on first connect
[MongoNetworkError: connection 5 to
cluster0-shard-00-00-shqnc.mongodb.net:27017 closed]
Here's how my server is set-up:
Keys.js
module.exports = {
mongoURI:
"mongodb+srv://Ahmed:<MyMongoDBAtlasPWD>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority"
};
Server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {
useNewUrlParser: true
})
.then(() => {
console.log("MongoDB connected!");
})
.catch(err => {
console.log(err);
});
app.get("/", (req, res) => {
res.send("Hello");
});
//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
And this is the code suggested by the MongoDB atlas website to be used:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Ahmed:<password>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
But, since I don't want to use mongoClient but rather mongoose, I am having some trouble and I cannot see why the code doesn't work;
EDIT 1: I have managed to connect using the Shell command(Check-out my answer). However, connecting through the app doesn't work and gives a different error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-01-shqnc.mongodb.net:27017] on first connect
[MongoError: bad auth Authentication failed.]
EDIT 2: I made a stupid mistake. I've forgotten to remove <> from the . All is good now.
The problem is that I was trying to connect using my MongoDB Atlas account password instead of the user password. Yes, those are 2 different things.
1. Click on Database Access
2. Edit the current user and modify the password
3. Use that password to connect to MongoDB Atlas
Make sure you have whitelisted your public IP. You can find that by googling "what is my ip".
This is the tasks.js code I'm trying to run:
/*jslint node:true*/
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://localhost:27017/tasks', ['tasks']);
router.get('/tasks', function (req, res, next) {
'use strict';
db.tasks.find(function(err, tasks) {
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
The code is meant to query and display all the contents of the json file.
When I replace the db localhost URL with this mLab URL:
var db = mongojs('mongodb://username:password#ds161008.mlab.com:61008/mytasklist_muhab', ['tasks']);
It works perfectly.
I assume there is a problem with the string. I looked up the connectionString standards in MongoDB docs and I couldn't locate the problem.
I haven't assigned any username or password to the local database.
Mongod is running fine and I am able to run commands on the same database using the Mongo shell without any problem.
According to mongojs documentation you may no need to use mongodb://localhost:27017 as part of your connectionString for local db can try by only dbName
like:
var db = mongojs('tasks', ['tasks'])
or
var db = mongojs('tasks')
var mycollection = db.collection('tasks')
and checked your connection established or not by using error or connect event
var db = mongojs('tasks', ['tasks'])
db.on('error', function (err) {
console.log('database error', err)
})
db.on('connect', function () {
console.log('database connected')
})
I am having trouble making node.js and mongodb with mongolab work on heroku. I have read other issues like How do I setup MongoDB database on Heroku with MongoLab? and How do I manage MongoDB connections in a Node.js web application? but I still can not set up my connection. In the logs it says [Error: failed to connect to ...]
I have takend the db, host and port from the MONGOLAB_URI process env.I have the following code:
var mongoUri = mongodb://heroku_app17328644:{password}#ds037518.mongolab.com //taken from process.env.MONGOLAB_URI
var host = 'mongodb://heroku_appXXXXXX:{password}#ds037518.mongolab.com';
var port = '37518';
var database = 'heroku_appXXXXXX';
Provider.db = new Db(database, new Server(host, port, { safe: true }, { auto_reconnect: true }, {}));
Provider.db.open(function(err, db){
console.log(db); //null
if (err) console.log(err);
else console.log('success');
});
What am I doing wrong ?
The core issue seems to be that you're trying to use a MongoDB URI as a hostname.
Here's how to connect using a URI and MongoClient:
var mongodb = require('mongodb');
var uri = 'mongodb://user:pass#host:port/db';
mongodb.MongoClient.connect(uri, function (err, db) {
/* adventure! */
});
Of course you'll want to substitute the user, pass, host, port, and db in the uri for your actual connect parameters. If you're using the MongoLab add-on for Heroku you can get the URI from the environment like this:
var uri = process.env.MONGOLAB_URI;
When using MongoClient safe mode is the default, so that option can be left out. To specify auto_reconnect simply pass it as a server option.
var mongodb = require('mongodb');
var uri = 'mongodb://user:pass#host:port/db';
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, db) {
/* adventure! */
});
Here's is how I do it. This way, my application connects to the "test" database on my development machine and the "mongolab" database when deployed and running on Heroku.
mongoose = require("mongoose");
mongoURI = 'mongodb://localhost/test';
mongoose.connect(process.env.MONGOLAB_URI || mongoURI);
In my own case, I queried the configuration settings heroku config and it turns out that the mongodb is added as MONGODB_URI.
So, I added process.env.MONGODB_URI to the uri such as:
var uri = process.env.MONGODB_URI || process.env.MONGOHQ_URL || process.env.MONGOLAB_URI;