Mongoose cannot connect to Openshift MongoDB - node.js

The logs in OpenShift displays MongoError cannot connect to undefined:27017
var mongoose = require('mongoose');
var url = process.env.OPENSHIFT_MONGODB_DB_URL +
process.env.OPENSHIFT_APP_NAME;
mongoose.Promise = global.Promise;
var connect = function () {
mongoose.connect(url);
};
connect();
var db = mongoose.connection;
db.on('error', function(error){
console.log("Error loading the db - "+ error);
});
db.on('disconnected', connect);

Related

I can't save or find a document into MongoDB using Mongoose

I'm using nodeJS for the first time, and I'm trying to do an application that connects to MongoDB via Mongoose.
I've installed MongoDB, NodeJS and Mongoose(via npm) successfully.
My problem is:
When I connect my node application through mongoose does not show any error, but when I try to insert a document, it just doesn't do anything at all. Freezes at the save line.
This is my code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
...
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB');
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var someModel = mongoose.model('someModel', {
name : String
});
app.get('/api/todos', function(req, res) {
var awesome_instance = new someModel({ name: 'awesome' });
console.log("about to save the document");
awesome_instance.save(function (err) {
if (err) return handleError(err);
});
});
app.post('/api/todos', function(req, res) {
});
...
app.listen(8080);
console.log("App listening on port 8080");
Using a mongo client I can see my db, but not the collection that the code should have created. Also my mongoDB detects the connection from nodeJS. I just don't know what could be happening.
This is what my server.js (node) is showing
$ node server.js
App listening on port 8080
about to save the document
GET /api/todos - - ms - -
This is my mongo client
$ ./mongo
MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
use exampleDB
switched to db exampleDB
show collections
exampleCollection
Thanks a lot in advance.
Let your get this and see if it works.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB', { useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var someModel = mongoose.model('someModel', {
name : String
});
app.get('/api/todos', async function(req, res) {
var awesome_instance = new someModel({ name: 'awesome' });
await awesome_instance.save()
});
app.post('/api/todos', function(req, res) {
});
app.listen(8080, ()=>console.log("App listening on port 8080"));

I am getting empty array as a response when i do get request

I am new to nodejs and express.When i try to do get request from the mongoose database in mlab.com i get an empty response.
my serve code is (app.js),
var express = require('express');
var mongoose = require('mongoose');
var app = express();
var db =mongoose.connect('mongodb://test:test#ds155695.mlab.com:55695/app');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected');
});
var user = require('./model/userModel');
var routers = express.Router();
routers.route('/getUSers').get(function(req,res){
user.find(function(err,users){
if(err) {
console.log(err);
} else {
res.json(users);
}
});
});
app.use('/api',routers);
app.listen(8000,function() {
console.log('server working');
});
My model is userModel.js
var mongoose = require('mongoose');
var app = mongoose.Schema({
firstName : String,
lastName : String
});
module.exports = mongoose.model('users',app);
can anyone help me where am i going wrong !

One mongo connection in multiple Node modules

I am trying to have all my Node modules share one Mongo connection, and am having trouble doing so. I've looked at some of the materials written about this already. Below is the main file, the Mongo helper file, and another file that tries to use the connection. The trouble is that when the route file tries to use the Mongo connection, db is null.
Mongo helper file:
var mongo = require('mongodb').MongoClient
var _db
function connect(callback) {
const host = '---'
const database = '---'
const user = '---'
const pass = '---'
const uri = 'mongodb://' + user + ':' + pass + '#' + host + '/' + database
mongo.connect(uri, (err, client) => {
console.log('Connected to Mongo')
_db = client.db(database)
return callback(err)
})
}
function db() {
return _db;
}
module.exports = {
connect: connect,
db: db
}
Main file:
var express = require('express')
var app = express()
var mongo = require('./helpers/mongo')
mongo.connect((err) => {
if (err !== null) {
console.log("Error connecting to Mongo: " + err)
process.exit()
}
})
var problems = require('./routes/problems.js')
app.use('/problem', problems)
app.listen(3000)
Route file:
var express = require('express')
var router = express.Router()
var db = require('../helpers/mongo').db()
router.get('/stuff', (req, res) => {
var problems = db.collection('problems')
res.send('working correctly')
})
module.exports = router
What about mongoose?
const mongoose = require('mongoose');
// connect to the database (mongodb)
mongoose.connect('mongodb:<host>/<db>', {useMongoClient: true});
mongoose.promise = global.Promise;
var db = mongoose.connection;
// Check for DB connection
db.once('open', function(){
console.log('Connected to Mongo Db');
});
// Check for DB errors
db.on('error', function(err){
console.log(err);
});

MongoDB-mongoose does not respond to REST API

I have a strange issue with MongoDB-mongoose, which does not respond to REST API
mongoose version - 4.11.3
Mongo DB shell version 3.4.6
Everything is local on my computer
Connection to Mongo DB is the following:
server.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});
...
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
The log "Connected correctly to db" is printed.
Schema (tasks.js)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskSchema = new Schema({
name: String
});
var Task = mongoose.model('Task', taskSchema);
module.exports = Task;
And finally taskRouter.js
var express = require('express');
var bodyParser = require('body-parser');
var Task = require('../models/tasks');
var taskRouter = express.Router();
taskRouter.use(bodyParser.json());
taskRouter.route('/')
.get(function (req, res, next) {
Task.find({}, function (err, task) {
console.log("result"+task)
if (err) throw err;
res.json(task);
});
})
.post(function (req, res, next) {
var task = new Tasks();
console.log ('the name is '+req.body.name);
task.name = req.body.name;
task.save(function(err){
console.log ("arrived there");
if (err)
res.send(err);
res.json({message: "Task created"});
});
})
As you see, everything is by the book .
But I never get any logs from task.save and Task.find
My 'morgan' logger shows just the following logs:
GET /api/tasks - - ms - -
POST /api/tasks - - ms - -
Postman is stuck on "Loading", until receives a timeout: Could not get any response.
All simple operation on the tasks collection in Mongo DB shell are performed without any problem.
What happens with mongoose?
Thanks in advance.
Try to create a separate file config.js with the following code :
module.exports = {
'database': 'mongodb://localhost:27017/yourdatabasename'
}
server.js:
...
var config = require('./config'); // get our config file
...
var mongoose = require('mongoose');
...
mongoose.connect(config.database, { useMongoClient: true });
mongoose.connection.on('open', function(err, doc){
console.log("connection established");
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});

How to use mongoose object in another node file?

I am new to node.js . I am trying to create one connection in server.js and use it in addAcction.js but got error while running "Software is not
a constructor", Please help me this?
//Server .js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/MSDN');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function callback() {
console.log("Connection with database succeeded.");
});
module.exports = db;
var SoftwareSchema = new mongoose.Schema({
SoftwareID: Number,
SoftwareName: String,
});
module.exports = mongoose.model('Software', SoftwareSchema);
//addAction.js
var Software = require('./Server').Software;
var Software1 = new Software({
SoftwareID : 1,
SoftwareName : "MNG123",
});
Software1.save(function(err){
if ( err ) throw err;
console.log("Software Saved Successfully");
});

Resources