node.jsmongodbopenshiftmongojs

how to query mongodb from nodejs via mongojs module ? (server is openshift)


I was trying out mongodb and nodejs on openshift, using mongojs to interface between nodejs and mongodb.

In mongoshell I ran "use nodejs" and defined a "scores" collection. I saved some data in it and its correctly showing.

In app.js file of nodeserver I have

self.routes['/db'] = function(req, res) {
var db = require("./db");
        db.scores.find(function(err,docs){res.send(docs);});        
    };

and in db.js file I have

var dbName = "/nodejs";
var databaseUrl = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +  process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" + process.env.OPENSHIFT_MONGODB_DB_HOST + ":" +  process.env.OPENSHIFT_MONGODB_DB_PORT+ dbName;
// "username:password@example.com/mydb"
var collections = ["scores"]
var db = require("mongojs").connect(databaseUrl, collections);
module.exports = db;

I am unable to get any data when I go to url mydomain.com/db

Can someone please point out what am doing wrong. The database is connecting. I am unable to find all from scores collection.

self.routes['/db'] = function(req, res) {
    var db = require("./db");
    db.scores.find(function(err,docs){res.send(docs);});        
};

Solution

  • The db connection configuration I saved in a separate file was the one causing error. This configuration worked and I was able to fetch db entries. Use either the commented out block OR the code below that. Both does the same thing. Just posting this answer for anyone trying out on openshift.

    self.routes['/db'] = function(req, res) {
            var dbName = "/nodejs";
            var connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +  process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" + process.env.OPENSHIFT_MONGODB_DB_HOST + ":" +  process.env.OPENSHIFT_MONGODB_DB_PORT + dbName;
            var db = mongojs(connection_string);
    
            /*
            var b = db.collection('books');    
            db.b.find(function(err, docs) {
               res.send(docs); 
            });*/
            db.collection('books').find(function(err,docs){
                res.send(docs);
            });
        };
    

    nodejs is the database name used in which the collection "books" were stored. Defined var mongojs=require('mongojs'); at the very top where all variables were declared, though it doesn't matter if its just declared before mongojs variable is used.