Getting Mongo to Connect to Express App - javascript

Yosemite Mongo user working through a MEAN book. I've been following the steps exactly, but the MongoDB isn't connecting as expected. I installed Mongo once before to mess around with importing data, but didn't get too far. Below is all the Mongo related code I have besides package.json:
In app.js I have require('./app_server/models/db'); and in that folder I have:
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
I am expecting to get
Express server listening on port 3000
Mongoose connected to mongodb://localhost/Loc8r
But instead get:
Mongoose disconnected
Mongoose connection error: Error: failed to connect to [localhost:27017]
I've tried changing a line to var dbURI = 'mongodb://localhost:3000/Loc8r'; because that's what my computer is using, but then get this error:
Mongoose disconnected
Mongoose connection error: Error: connection closed
Any help is much appreciated thanks.

Mongo was missing the folders it needed MongoDB not working. "ERROR: dbpath (/data/db) does not exist."
Then the server had to be run with "mongod"

Related

connectIin to mangodb with js unlimited time

Good morning everyone ,
i tried to create a new data base with mangodb version msi 6.0 i made this code below:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
the first error is about MongooseServerSelectionError: connect ECONNREFUSED localhost:27017`
i changed the local host with the ip adress 127.0.0.1
NOW IT DOES NOT SHOW ANY ERROR BUT THE PROCESS TAKE UNLIMITED TIME !!!
THAKS!!!
Solution for the UNLIMITED TIME EXECUTION PROBLEM
please check if you are actually running the mongo on given port, and see:
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
https://www.mongodb.com/docs/manual/reference/connection-string/

How to run Mongoose/MongoDB updates/queries in node.js backend without starting the server? (Heroku Scheduler)

I have an app hosted on Heroku (https://trendedge.app) (front-end and back-end are separate apps), and am working on implementing the Heroku Scheduler for basic tasks such as sending emails, and running updates on my MongoDB Atlas database (hit an API, update MongoDB w/ Mongoose).
For the MongoDB updates, I currently hit an admin route on the front-end, and the updates start running on the backend. Easy PZ.
To setup the Heroku scheduler, though, it requests a node.js command (seen here) ...
... and this makes sense, but if my connection to MongoDB atlas is made upon the starting up the server ('npm start', i.e. 'node index.js'), then how do I run a node command to update MongoDB, when the server hasn't been started yet?
For example, if I run "node updateDB.js", it will error out because there is no server running, and connection to Mongo has yet to be established.
Any insight to how I can setup/test these scheduled node functions (without starting up the server?) would be greatly appreciated.
Can require just the necessary startups from index.js in schedule.js. In this instance just the validation and mongodb startups
for a run single file and connect with database to perform some task. you can try this way.
mongodb = require('mongodb');
config = module.exports = require("/home/node/myclass/crons/config.json");
var MongoClient = mongodb.MongoClient;
ObjectId = module.exports = mongodb.ObjectID;
var dbConnUrl = 'mongodb://' + config.DB_USERNAME + ':' + config.DB_PASSWORD + '#' + config.DB_HOST + ':' + config.DB_PORT + '/' + config.DB_NAME;
console.log("dbConnUrl >> ", dbConnUrl);
MongoClient.connect(dbConnUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, dclient) {
if (err) {
console.log("mongodb connection error >> ", err);
process.exit();
} else {
db = module.exports = dclient.db();
console.log("---------------------------mongodb connected-----------------------");
run();
}
});
async function run() {
await db.collection("notification_token").find({}).toArray();
process.exit();
}

Error: read ECONNRESET when connected to a mysql server with Node.js

I'm trying to establish a simple connection to my database with the mysql npm package. At first glance, everything works fine and I can get the information I need, however, if I leave the server running for some time I get the following error:
Error: read ECONNRESET
at TCP.onStreamRead
const express = require('express');
const app = express();`
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'XXXX.mysql.database.azure.com',
user: 'XXXXX',
password: 'XXXXX',
database: 'XXXXX'
})
db.connect((err)=>{
if(err){
console.log(err.message);
} else {
console.log('Connected to the database');
}
})
As far as I understand the problem stems from the database connection being in idle mode. Do I need to configure the Azure server or is there something else I need to do?
Couple of things to try:
You can try creating connection pool instead of **createConnection**
mysql.createPool({});
Modify your package.json like below:
"dependencies": {
"mysql": "git://github.com/mysqljs/mysql#e3e123e9af7c0829a6c1417d911572a75b4a5f95"
},
It is described in detail here:
Bad handshake or ECONNRESET Azure Mysql Nodejs
https://social.msdn.microsoft.com/Forums/en-US/c8fedbcc-909d-41ce-8c72-0374f76fdf82/cannot-connect-from-nodejs?forum=AzureDatabaseforMySQL
Hope it helps.

Node.JS Web Application Create MongooseDB Connection

I'm trying to create a connection to MongoDB from a Node.JS application but I can't get the connection working. I just get errors saying:
TypeError: mongoose.createConnection is not a function
Same for just mongoose.connection also..
I just have a serivce class and I'm trying to create a connecting inside of it:
const mongoose = require('mongoose');
export class MongoDbService{
constructor(){
db = mongoose.createConnection(url)
.on('error', console.error.bind(console, 'connection error:'))
.once('open', function callback() {
console.log('db connection open');
});
console.log(db);
}
Surely this is possible ???
I'm trying to build a web application that talks to mongodb, nothing fancy at all.. Mongoose v5.1.6 is install also.

Can't start MongoDB on localhost for node.js

I am a beginner to node.js and MongoDB. I am trying to setup a basic project like so.
In my project dir I run node init, accept the default values and then run npm install --save mongodb. In my index.js I have the following code:
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3333/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Now when I run node index.js I get the following error:
failed to connect to server [localhost:3333] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3333]
I have tried changing the port number but still get the same error. What am I doing wrong here?
By default the MongoDB server is running on port 27017. You need to change the connection string to mongodb://localhost:27017/mydb.
First you need to install MongoDB if you don't already have it installed. Visit MongoDB site to download.
Follow the instructions there on how to start it up and running, after that try running your app again.
Also by default MongoDB runs on port 27017 so your url should point to localhost:27017.
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

Categories