Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

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

In mongoshell, I executed "use nodejs" and assigned a "scores" collection. I have inserted the data in it and its correctly displaying.

In the app.js file of nodeserver, I have the following code:

self.routes['/db'] = function(req, res) {

var db = require("./db");

        db.scores.find(function(err,docs){res.send(docs);});        

    };

and in my javascript db.js file I have the following code:

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:[email protected]/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 you please guide me on where I am doing wrong. The database is connecting. I am not able to find all the data from the scores collection.

self.routes['/db'] = function(req, res) {

    var db = require("./db");

    db.scores.find(function(err,docs){res.send(docs);});        

};

1 Answer

0 votes
by (107k points)
edited by

The way you have saved your database collection in a separate file is not correct. Refer to the following code:

self.routes['/db'] = function(req, res) {

        var dbName = "/nodejs";//database name

        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);//collelction name is books

        });

    };

If you want to learn more about MongoDB then go through this MongoDB course for more insights.

Also, have a look at this professional Full Stack Development Course, designed to enhance your skills in the field.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 15, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Mar 14, 2020 in Web Technology by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...