Mongoose connect method fails on simple Node Server. Express, Mongoose, Path - node.js

This is the first time I'm running node with mongoose. I'm following some tutorials in this backbone book and I'm up to this chapter on creating a restful api using express, mongoose and I'm following the code exactly I've even come to copying and pasting but it's still not working. Here is the code:
http://addyosmani.github.io/backbone-fundamentals/#creating-the-back-end
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
path = require( 'path' ), //Utilities for dealing with file paths
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//parses request body and populates request.body
app.use( express.bodyParser() );
//checks request.body for HTTP method overrides
app.use( express.methodOverride() );
//perform route lookup based on url and HTTP method
app.use( app.router );
//Where to serve static content
app.use( express.static( path.join( application_root, 'site') ) );
//Show all errors in development
app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
});
//Start server
var port = 4711;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
// Routes
app.get( '/api', function( request, response ) {
response.send( 'Library API is running' );
});
//Connect to database
mongoose.connect( 'mongodb://localhost/library_database');
//Schemas
var Book = new mongoose.Schema({
title: String,
author: String,
releaseDate: Date
});
//Models
var BookModel = mongoose.model( 'Book', Book );
I've been poking around on stack overflow and other sites trying to resolve the issue but nothing I found seemed to allow me to connect to the mongodb.
The first error is:
events.js:72
throw er; // Unhandled 'error' event
^
Error: failed to connect to [localhost:27017]
at null.<anonymous> (/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:536:74)
at EventEmitter.emit (events.js:106:17)
at null.<anonymous> (/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at EventEmitter.emit (events.js:98:17)
at Socket.<anonymous> (/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:411:14
at process._tickCallback (node.js:415:13)
This change seems to fix that issue:
mongoose.connect( 'mongodb://localhost/library_database', function(err) { if (err) console.log(err); } );
After that express works but mongodb fails to connect:
Express server listening on port 4711 in development mode
[Error: failed to connect to [localhost:27017]]
I tried changing to this:
mongoose = require( 'mongoose' ).Mongoose;
I also tried running mongod in the cli with some variations on options in the cli but that seems to just bring up the help page. I'm totally stuck... Any help would be greatly appreciated. Thanks in advance.

You need to actually successfully get mongod running and listening for connections. Just type mongod with no options, hit ENTER, and let it run. Then in a separate terminal start your express app. Note that mongod is the mongodb server daemon whereas mongo is the command line client where you can run an interactive REPL and issue database commands.

You need to install the database itself. Refer here for mongodb installation guide.

Related

Deploying to Heroku: Env variables are undefined

Disclaimer: This is my first question so any helpful critiques on how to make future ones better is welcome. I'm also relatively new to programming and stack overflow so forgive me if I don't understand some concepts or my question is vague or not understandable.
My Problem: I am trying to deploy my MERN stack app to heroku (im using mongodb atlas) and in my heroku logs its saying that my mongodb uri is undefined instead of a string. My uri is set to an environment variable, and everything works fine on my local machine. When push my code up to heroku though, the uri is suddenly undefined. I've researched the problem and come across various solutions but none of them work. The most common solutionn was to set the env variable on heroku in the config vars section, but that doesn't work either.
Error Message: Error [MongooseError]: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
My Server Code:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose')
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
console.log(uri)
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB database connection made, yay!')
})
const exerciseRouter = require('./routes/exercises')
app.use('/exercises', exerciseRouter);
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
When I run this on my local machine the console.log() function prints out the correct uri and the database connection is successful but the problems still occur when I push this code to heroku.
Let me know if I should provide any more details on the problem, this was all I could think of that would be helpful. Thanks!

facing difficulty in creating my server through nodejs express

I am a beginner in Node js and Express and I was trying to create my server following this tutorial : https://codeforgeek.com/express-nodejs-tutorial/
This is my server.js code:
var express = require("express");
var app = express();
var server = app.listen(3000, function() {
console.log("We have started our server on port 3000");
});
error on cmd
It seems like it's the use of the ejs package without following the next steps of the tutorial, I get the same error at Step 3:
We have started our server on port 3000
/..stackhelp/59715144/node_modules/express/lib/application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot read property 'handle' of undefined
at Function.app.handle (/Users/tamebadger/Projects/stackhelp/59715144/node_modules/express/lib/application.js:119:15)
at Server.app (/Users/tamebadger/Projects/stackhelp/59715144/node_modules/express/lib/express.js:28:9)
at emitTwo (events.js:125:13)
at Server.emit (events.js:213:7)
at parserOnIncoming (_http_server.js:602:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
Removing the ejs package would solve your problem if it was an option (you need it later in the tutorial)
Our of interest sake, see if you still get the issue if you add the next part of the tutorial:
app.get('/',function(req,res){
res.send('Hello world');
});

Node.js server will not start but seems to connect to DB

I have a node application that is not working though did work about 2 hours ago (no code changes). Also no changes to the server, I only ran another node application on the same port but that process has been killed.
Command to start node node server
server.js
var app = require('./server/index');
app.set('port', process.env.PORT || 3000);
var server = app.listen(8080, function() {
console.log('Express server listening on port ' + server.address().port);
});
app.js (stripped down)
const express = require("express"),
mongoose = require("mongoose"),
app = express();
mongoose.connect(config.db, {autoReconnect: true}, (err) => {
if (!err) console.log('MongoDB has connected successfully.');
});
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
var authRoutes = require('./routes/auth.js');
authRoutes(app, passport);
module.exports = app;
Output when starting node process
(node:4341) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:4341) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
MongoDB has connected successfully.
Solved it, seems that using node server was going directly into my server directory and running app.js file note the server.js file I wanted it to. Instead I had to run node server.js

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

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.

mongoose never stops loading

I am on windows. The local database is running fine, I can write to and find collections with the mongo command line tool. The local nodejs is running fine as well. When I remove my mongoose code, I can reach my endpoints.
When I start the node server with the mongoose code, I get this message:
23:05:57 web.1 | started with pid 20860
23:05:58 web.1 | { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
23:05:58 web.1 | js-bson: Failed to load c++ bson extension, using pure JS version
23:05:58 web.1 | Node app is running at localhost:5000
The server starts, although the error is worrisome (have tried to fix it for a good while, no luck yet), but it doesn't seem like a fatal error.
When I try to access one of my endpoints, either through Postman API, the browser or my application, it tries to connect forever. I can also see in mongo that a connection to the db never is made.
This is the code I have right now:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
mongoose.connection.on("open", function(ref) {
console.log("Connected to mongo server.");
return start_up();
});
mongoose.connection.on("error", function(err) {
console.log("Could not connect to mongo server!");
return console.log(err);
});
mongoose.connect("mongodb://localhost/test");
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
app.get('/', function(request, response) {
response.send("Hello StackOverflow");
});
I've been sitting quite a few hours over the last three days trying to make it work, feels like I've been through every remotely relevant google search at this point. Hope you can help me out. :)
EDIT: If I go with mongoose version 3.8.3. The MODULE_NOT_FOUND error disappears. But it doesn't fix the never ending load.

Resources