Node.js script not getting connected to Mongodb database in localhost - node.js

I have following test code to run mongodb along with node.js while creating rest api
MONGO.JS
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/smartRideDb');
// create instance of Schema
var mongoSchema = mongoose.Schema;
// create schema
var userSchema = {
"id" : String,
"email" : String,
"password" : String
};
// create model if not exists.
module.exports = mongoose.model('user',userSchema);
index.js is defined as
var mongoOp = require("./models/mongo");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
app.use('/' , router);
var port = process.env.PORT || 3000;
/**
*
*
*
*/
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code)
{
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
/**
*
*
*
*/
router.get("/",function(req,res)
{
res.json({"error" : false,"message" : "Hello World"});
});
//route() will allow you to use same path for different HTTP operation.
//So if you have same URL but with different HTTP OP such as POST,GET etc
//Then use route() to remove redundant code.
router.route("/users").get(function(req, res)
{
var response = {};
mongoOp.find({},function(err,data)
{
if(err)
{
response = {"error" : true,"message" : "Error fetching data"};
}
else
{
response = {"error" : false,"message" : data};
}
res.json(response);
});
});
app.listen(port);
console.log("Listening to PORT " + port);
When i run i get this error
Muhammads-MBP:Api Umar$ node index.js
Listening to PORT 3000
/Users/Umar/Desktop/Projects On List Data/Creative Studios/School Ride/Api/node_modules/mongodb/lib/server.js:242
process.nextTick(function() { throw err; })
^
Error: connect ECONNREFUSED 127.0.0.1:27017
at Object.exports._errnoException (util.js:890:11)
at exports._exceptionWithHostPort (util.js:913:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1057:14)
Why is mongodb not gett

You may want to try to ensure the MongoDB has properly setup first by following
MongoDB is installed successfully (OSX guide here)
Run mongod in terminal after installed to run the MongoDB
Run mongo in another terminal, and you should be able to see something similar.
.
MongoDB shell version: 3.2.4
connecting to: test

Try calling the connection to mongo before app.listen, mongoose open a pool of connections by default for attend the requests
mongoose.connect('mongodb://localhost/dbname', function(err) {
if (err) throw err;
app.listen(port);
console.log("Listening to PORT " + port);
});

Most common troubleshooting steps:
Configured localhost incorrectly somewhere, so try changing your connection string to mongodb://localhost:27017/smartRideDb.
Check if mongod is running at that port.
Check if some other process is using that port.

Related

Make post request to Mongodb Atlas using Nodejs

I was familiar with MongodB for CRUD operation. Here, I'm trying to make simple post request on mongodB atlas but I want to know where I have done error for the connection and posting data to MongodB atlas.
Model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let quizSchema = new Schema({
title: {
type: String,
},
description: {
type: Number,
},
question: {
type: String,
},
});
const Quiz = mongoose.model("Quiz", quizSchema);
module.exports = Quiz;
index.js
I'm trying to create the database collection name "QuizDatabase" and insert the data to it.
var express = require("express");
var bodyParser = require("body-parser");
const Quiz = require("./views/model/model");
var Request = require("request");
var app = express();
app.use(bodyParser.json());
const MongoClient = require("mongodb").MongoClient;
const uri =
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connect(uri);
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/new/", function (req, res) {
Quiz.collection("QuizDatabase").insertMany(req.body, function (err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new quiz.");
} else {
res.status(201).send(JSON.stringify(body));
}
});
});
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({ error: message });
}
You dont have to use mongo client if you are already using mongoose.
In index.js file just import the model
const Quiz = require("./model");
And you are already using mongoose to connect to db when you write mongoose.connect(uri); You don't have to use client.connect() again.
Query to insert -
Quiz.insertMany(req.body);
Your index file should look like this -
const Quiz = require("./views/model/model");
var Request = require("request");
var app = express();
app.use(bodyParser.json());
const uri =
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
mongoose.connect(uri);
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/new/", function (req, res) {
Quiz.insertMany(req.body, function (err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new quiz.");
} else {
res.status(201).send(JSON.stringify(body));
}
});
});
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({ error: message });
}
There are several reasons.
Connection Issues to the MongoDB database.
To check this insert app.listen() into mongoose connect. This would make sure you can only run development on your preferred PORT only when it has successfully connected to your Database. e.g From your code
mongoose.connect(uri)
.then(() => {
//listen for PORT request
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
}).catch((error) => {
console.log(error);
});
Try purposely using the wrong Username or Password and see if you get this error:
MongoServerError: bad auth : Authentication failed.
at Connection.onMessage (/Users/user/Documents/..<pathway>../connection.js:207:30)
*
*
*
*
ok: 0,
code: 8000,
codeName: 'AtlasError',
[Symbol(errorLabels)]: Set(1) { 'HandshakeError' } }
If you don't get this error then you have a connection problem. To solve this, I added my current IP ADDRESS and 0.0.0.0/0 (includes your current IP address) at the Network Access page. So you click on MY CURRENT IP ADDRESS and confirm upon setting up the network. Go to NETWORK ACCESS, click on add new IP ADDRESS, input 0.0.0.0/0 and confirm. Then try using the wrong username or password in the URI link given to you to see if it gives the above-expected error, then you can now correct the Username and Password, and npm run dev or npm start (However you configured it in your package.json file).
Code issues
First of I would correct your Model.js file from this:
const Quiz = mongoose.model("Quiz", quizSchema);
module.exports = Quiz;
to this:
module.exports = mongoose.model("Quiz", quizSchema);
I can see why yours can work, but it may be an issue as you want to get the schema upon accessing the whole file.
Secondly, I would correct the code for Posting and you can do that in 2 ways using the asynchronous method. Which depends on the method of assigning the req.body.
Way 1:
app.post("/new/", async (req, res) => {
const { title, description, question } = req.body;
//adds doc to db
try {
const quiz = await Quiz.create({ title, description, question });
res.status(200).json(quiz);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
OR
Way2:
app.post("/new/", async (req, res) => {
const quiz = new Quiz(req.body);
//adds doc to db
try {
const savePost = await quiz.save();
response.status(200).send(savePost);
} catch (error) {
response.status(400).send(error);
}
});
NOTE: You don't necessarily have to create a named database and collection in Mongo Atlas before starting the project. The URI given to you covers that if there are no problems with the connection to the DB or the Code.
based on your code
URI:
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
would create a database called: QuizDatabase and collection called: quizs (MongoDb always creates the plural word from the model given and makes it start with lowercase (i.e from your Model.js, the mongoose.model("Quiz"))).
If no database is named in your URI, then a database called test is automatically created for you as a default database, with the collection name being the mongoose.model("") given.
CONCLUSION
This should solve at least 90% of your issues, any other creation/POST problems is currently beyond my current expertise. Happy Coding 🚀🚀🚀

Can't get response from Firebird in Node Express Server

I'm trying to establish a connection between my node express server and a Firebird database from an external server. I'm using this node-firebird library
This is my code on my index.js:
require("dotenv").config(); //Environment variables
const express = require("express");
const morgan = require("morgan");
const Firebird = require('node-firebird');
//Express Initilization
const app = express();
//MORGAN Configuration
app.use(morgan("dev"));
app.use( express.json() );
app.use( express.static("public") );
const options = {
"host" : 'externalddns.ddns.net',
"port" : 3050,
"database" : 'c:/database/databaseName.fb',
"user" : 'SYSDBA',
"password" : 'masterkey',
"lowercase_keys" : false,
"role" : null,
"pageSize" : 4096
};
Firebird.attach(options, function(err, db) {
if (err) {
throw err;
}
const query = "SELECT * FROM MYTABLE";
db.query(query, function(err, result) {
if(err){
console.log(err);
}
console.log(result);
// Close the connection
db.detach();
});
});
app.listen(process.env.PORT, () => {
console.log("Server running on port " + process.env.PORT);
});
I already open 3050 port on the external site router and firewall. The connection is working because if I select another path for the database and I do Firebird.create(.....) the database file is being created on the path specified. But I'm not getting any response from the console.log(result) on the db.query, not even an error. The only msg on the console is Server running on port MYPORT.
I can force an error if I change the query to select for a table that doesn't exist in the db. So the code is working but when it seems to be everything ok I don't get any response.
The database file is ok because is working for another service.
Is it possible that something on my pc is blocking the response? Like firewall or something. Any help would be appreciated.
I already know where the problem was. That library was for firebird 2.5+ version and my firebird server version was 2.1. -_-

Connection to MongoDB server using Node is unresponsive on localhost

I am trying to connect my node.js game to a MongoDB cluster so that I can store username and passwords. I already have the a mock DB stored locally using express + socket.io. I am trying to set up MongoDB atlas to store the usernames + passwords so that when the local host closes, the data won't disappear.
I've tried the following Developing A RESTful API With Node.js And MongoDB Atlas word for word. When I test my connection if it was successful, I enter on terminal:
node app.js
My server starts as expected and prints server started. From this tutorial, I should either see an error or a successful connection message. However, when I start the server, I don't see either. I am having trouble debugging this because I am not getting any response at all.
Here is the beginning of my app.js file for context.
// Express code
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var MongoClient = require('mongodb').MongoClient;
const CONNECTION_URL = *uri here*
const DATABASE_NAME = "bunnyCrossing";
var timeRemaining;
// If query is '/' (nothing)
app.get('/',function(req,res){
res.sendFile(__dirname + '/client/index.html');
});
// If query is '/client'. Client can only request things from client folder
app.use('/client',express.static(__dirname + '/client'));
// replace the uri string with your connection string.
var database, collection;
app.listen(3000, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
collection = database.collection("people");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
});
// Server starts listening on port 2000
serv.listen(2000);
console.log("Server started");
I should see when I run node app.js:
server started
Connected to `bunnyCrossing`!
But I just see:
server started
Either app.listen is not being called or you must hit localhost:3000 to invoke the callback to connect to mongo database.
Either remove serv.listen or add a callback to serv.listen as such and remove app.listen.
serv.listen(2000, function(err) {
if (err) console.log(err);
else {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
collection = database.collection("people");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
}
})

socket.io .authorization error on live server but not in localhost

I am new to node js and socket.io. i am implementing chat module on my website using node js and socket.io. I have successfully implement it on my localhost and it's working fine but after uploading files on the live server it doesn't work.
The error i am getting while running app.js file on server-
var chatpage=io.of('/chatpage').authorization(function (handshakeData, callbac
^
TypeError: Object # has no method 'authorization'
here is my app.js file code-
var express = require('express');
var app = express();
var socket = require('socket.io');
var server = app.listen(3000);
var io = socket.listen(server);
var async = require('async');
var mysql= require('mysql');
var pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'admin',
database : 'mychat'
});
var chatserver=require('./chatserver.js');
var chatpage=io.of('/chatpage').authorization(function (handshakeData, callback) {
console.dir(handshakeData);
handshakeData.page = 'chatpage';
callback(null, true);
}).on('connection', function (socket) {
console.dir(socket.handshake.page);
chatserver.getUserFeeds(chatpage,socket,io,pool,async);
});
and connection on client page -
var socket = io.connect('http://localhost:3000');
var chatpage=socket.of('/chatpage')
.on('connect_failed', function (reason) {
console.error('unable to connect chatpage to namespace', reason);
})
.on('error',function(reason){
console.error('unable to connect chatpage to namespace', reason);
})
.on('reconnect_failed',function(){
})
.on('connect', function () {
console.info('sucessfully established a connection of chatpage with the namespace');
chatpage.emit('senddata',{user_id:user_id,room_id:room_id});
});
Please help me out where i am doing wrong.

ReferenceError for Heroku MongoLab Connect

I am very close to an express app working in a sandbox environment on Heroku with a MongoDB addon..
I am still seeing a ReferenceError in the log, which seems to be the reason for the app crashing.
The first error was regarding this configuration:
//MongoDB
var mongodb = require('mongodb');
var db;
var MONGODB_URI = process.env.MONGOLAB_URI;
var PORT = process.env.PORT;
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
app.listen(PORT);
console.log('Listening on port ' + PORT);
});
var testColl = db.collection('test');
That led to the log reading a TypeError, probably because db was defined locally..
app[web.1]: var testColl = db.collection('test');
app[web.1]: TypeError: Cannot call method 'collection' of undefined
And the recent error was a ReferenceError:
app[web.1]: var db = database;
app[web.1]: ReferenceError: database is not defined
Probably because database is defined globally, but not referenced within the context of the connection..
//MongoDB
var MongoClient = require('mongodb').MongoClient,
var Server = require('mongodb').Server;
var mongoUri = process.env.MONGOLAB_URI;
var port = process.env.PORT;
var db = database;
var mongoclient = new MongoClient(new Server(mongoUri,
{ 'native_parser' : true }));
var testColl = db.collection('test');
mongoclient.open(function (err, mongoclient) {
if (err) throw err
app.listen(port);
console.log("Express server started on port " + port);
});
How can I reformat the code to launch this app on Heroku?
Your first example looks close to working, but there's one thing wrong. mongodb.connect is an asynchronous call, which means it returns right away. That's why it has the callback parameter. Because the code runs so fast, it doesn't have time to actually connect to the database before you try to use the db object, which is what causes your crash in the first set of code.
If you move your database call inside the callback, it should work.
Edit: This is in reply to your comment, but I can't include much code in another comment, so you get an edit.
It really depends on your use case, but I realize that's not very helpful. So here's one way you could do it:
module.exports = function() {
return db;
};
By doing so, you would be able to require it from another file, and use it as such:
var http = require('http');
var db = require('./db.js');
http.createServer(function(req, res) {
db().collection('test', function(err, collection) {
console.log(err, collection);
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('We got it! Unless there is an error...\n');
});
}).listen(8080);
There's definitely ways to improve upon that, but it should get you started.

Resources