I am having issues connecting my express app to MongoDB via Mongoose. There is no complicated set up, its fairly basic:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/homeApp');
var db = mongoose.connection;
db.on("connecting", function(){
console.log("Connecting to DB...");
});
db.on('connected', function(){
console.log('Connected to db');
});
db.on('error', function(error){
console.log('Error');
});
Simple enough, right? But none of these events are being fired. Mongo is running ok and it's on the default port. I have also tried changing localhost to 127.0.0.1 and checked the contents of my etc/hosts file and all seems ok. If I mangle the URI string to something like:
'mongoldb://lclhost/homeApp'
I get an error saying it cannot connect, which is to be expected so it seems like a connection is being made/attempted but nothing is happening.
I've logged the contents of db.Db to the console and noticed this connected: false, which suggests it's not even attempting a connect?
Any ideas? This is Mongoose 4.7.1 running on macOS Sierra 10.12.5.
Thanks in advance!
Figured it! I tried using the mongodb client without mongoose and everything worked as expected, so I knew the connection was ok and that left the blame with mongoose.
Turns out I was not using 4.7.1 as I had thought, and that just running npm install mongoose --save had in fact installed version 3.x, which is not compatible with the latest version of MongoDB according to the Mongoose docs. http://mongoosejs.com/docs/compatibility.html
Upgrading the version number in my package.json file to 4.7.1 fixed the issue.
the mongoose.connect method takes in a callback, which you could use to check the connection:
mongoose.connect(uri, options, function(error) {
// Check error in initial connection.
if (error) {
console.log(error);
} else {
console.log('connected ok');
}
});
I think your connection is being created, but your db.on events are not being triggered.
Related
I recently ran into this problem. When I try to run my Node.js app, I get this error MongooseServerSelectionError: connect ETIMEDOUT. It also said type: 'ReplicaSetNoPrimary'. For the past few months it was working perfectly and I had never got this error. I am using MongoDB Atlas for the database and Mongoose for its driver. I am using the latest version of Mongoose.
Here is my app.ts:
const CONNECTION_URL = "mongodb+srv://name:<password>#cluster0.vyegx.mongodb.net/MyApp?retryWrites=true&w=majority"
mongoose.connect(CONNECTION_URL).then(_INIT_)
async function _INIT_(){
const server = app.listen(PORT, ()=>{
console.log("listening on port "+PORT+"...")
});
const io = new Server(server);
}
I have tried to whitelist my ip, but it's not working.
UPDATE It works perfectly with no errors in Heroku but when I try to run it from my computer it gives an error.
need to set useUnifiedTopology: false
I am unable to pass requests with postman, and the error message is the one being printed on console. Before applying then method I was able to see the connection successful mssage but still wasn't able to get/post via postman
//database connection
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true }).then(()=>{
console.log("connection successful")
}).catch((error)=>{
console.log("Error occured on connection")
});
Requiring the connection via
const mongoose = require("mongoose");
and the MONGO_URL mentioned in .env file is
MONGO_URL = mongodb+srv://username:password#cluster0.8noo9.mongodb.net/dbname?retryWrites=true&w=majority
been stuck here for a while. I am setting up mongoose for the first time
It was due to not whitelisting m IP. If anyone has the same issue try it first. Go to mongodb and whitelist your IP in security -> network connections
I'm trying to use the mysql module to connect to my database. But everytime, I get the following error: read eCONNRESET There is problem. (Note, that last part is from my console log. See below.)
I don't think this is a problem with database security settings. I've been trying to connect to my new database (hosted on AWS) for the last several days with no luck. Then, just now I attempted to connect to an Azure database that has been running smoothly for a couple years. Same problem: read eCONNRESET.
By the way, if I randomly change the host string to something invalid, my code returns an error saying the host wasn't found. So that tells me it's working to some extent.
I'm very new to the coding world and need all the help I can get.
Here's my code:
console.log('starting Launch');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '....windows.net',
user : 'test',
password : 'test',
port : '1433'
})
console.log('step2')
connection.connect(function (err) {
if (!err)
console.log("conncetd");
else
console.log(err + "There is problem");
});
Copy full error message.
Check connectivity to your DB instance, use nmap (linux) or telnet (windows). If you can't reach host - check your local machine and server firewall, restrictions. If you can, go to 2.
Try to use different MySQL client, MySQL WorkBench, HeidiSQL, DBeaver.
If you can't - than something wrong with MySQL configuration. If you can, go to 3.
Copy info about: OS, node version, mysql module version.
you could try
mysql.createPool({});
instead of
mysql.createConnection({})
So, I am wondering if there is a way to connect to the mongoDB I have setup in my Cloud9 from an html. I mean, I have already connected to the db from the terminal and everything is working like a charm but I need to do some stuff inside my script in an html document and when I try calling the function which contains this code it does nothing
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/ingesoft', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
I have saved the same code into a "file.js" and ran it from console using node file.js and it outputs into the console log "successfully connected to the database", plus the terminal which is running mongo's connection shows me one more connection to the db. The thing is, when I try to run that code inside my script it doesn't work. Sorry for my ignorance I am new to mongo.
Any help would be much appreciated
To simplify your question, here's what's going on:
node file.js containing the code in your question is working
pasting the same code to your html file is not
So, getting to the bottom of the issue, let's ask first: what's the difference between running node file.js and putting the code in html?
The difference is that node ... is running on your Cloud9 workspace (let's call it the server machine).
Your MongoDB server is also running on that server machine
The mongodb npm package you installed is also present on the server machine
The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your server
whereas with the code on your browser:
The code is being run on your customer's machine
That machine doesn't have your Mongodb server
Browser's usually don't support require
You can do requires if you bundle code and use something like webpack or browserify. Did you perhaps do that?
If you did indeed package everything, was the mongodb package that you're requiring packaged?
Can the mongodb package be run from the client side?
The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your customer's machine
Basically, as you can see from the above, the two are very different.
If you want to talk to your db, a lot of people go the following route:
Make a server application that implements some form of REST API
That REST API talks to your DB
Your client code knows how to talk to the REST API and get the required data
That way, you only talk to your MongoDB using your server, and the client can talk to your server via the internet.
This is, of course, an oversimplification, but I hope this resolves your confusion.
I'm trying to use Nodejs to get data from Meteorjs mini mongo database. Here is my code:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:3001/meteor', function(err, db) {
if(err) throw err;
console.log("Connected to Database");
var test = db.collection("apps");
test.insert({"_id":"selfDefinedID"}, function(err,docs){
console.log("docs inserted");
console.log(docs);
});
test.find({"_id":"selfDefinedID"}).toArray(function(err,docs){
console.log("docs founded");
console.log(docs);
});
});
Insert data works fine. But, I can't retrieve data from meteor mini mongo database. And I got an error:
{ [MongoError: Connection Closed By Application] name: 'MongoError' }
Is it possible to retrieve Meteor mini mongo data using Nodejs? If possible, how?
The database meteor uses is a normal mongo database. You can connect to it like any other mongo db. If you are still in development mode, then the database runs at mongodb://localhost:3001/meteor, otherwise, in a bundled app, it's just the db you specified yourself using MONGO_URL.
On a windows machine, I created a new, blank, meteor project, and started it up. I then created a test script, npm installed the mongodb library, and ran your script and it worked fine. First run I get "docs inserted" and "docs founded", on subsequent runs obviously the insert is failing, but the find still works.
So two questions, first is this the same script your getting the error with? And two, if you create a blank meteor project and try it do you get the same error?