1

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);});        
};
codefire
  • 393
  • 1
  • 3
  • 13
  • 1
    Welcome to Stack Overflow! While your question seems well thought-out, I'd advise changing the title of your question to better describe the problem you're facing, such as "Node.js with MongoDB and Openshift not routing correctly". – Daniel Attfield Aug 31 '14 at 18:31
  • Thanks for the suggestion. I think that would be more helpful for someone in the future. Will change it accordingly. Also its not about routing. Just unable to query correctly from nodejs to mongodb via mongojs – codefire Sep 01 '14 at 15:14

5 Answers5

1

I think that you should use the collection method to use your score collection. Like the following:

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

Or use the toArray function to be sure to retrieve an array of objects.

db.collection('scores').find().toArray(function(err, docs) {
    console.dir(docs);
    res.send(docs)
}
Adlen Afane
  • 1,422
  • 14
  • 24
  • Yes, thank you for your response. The way I tried to save my db connection configuration in a seperate file was wrong. – codefire Sep 01 '14 at 16:31
  • 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); }); }; – codefire Sep 01 '14 at 16:32
1

this is how we connect to our MongoDB server:

//app.js
var databaseUrl = "mydb"; // "username:password@example.com/mydb"
var collections = ["users"]
var db = require("mongojs").connect(databaseUrl, collections);



 db.users.find({email: "abcd@gmail.com"}, function(err, users) {
  if( err || !users) console.log("No female users found");
  else users.forEach( function(femaleUser) {
    console.log(femaleUser);
  } );
});
Deepika Chalpe
  • 404
  • 8
  • 19
0

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.

codefire
  • 393
  • 1
  • 3
  • 13
0

Using MongoClient.

//test is the database and students is the collection inside test.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
    console.log("Successfully connected to MongoDB ");
    var cursor = db.collection('students').find({});

    cursor.forEach(
        function(doc) {
           console.log("JSON doc: "+doc);
        },
        function(err) {
            console.log("Error");
            return db.close();
        }
    );

});
koti bajjuri
  • 81
  • 1
  • 4
0

You can use the below code in Node to connect to a MongoDB collection and return the results as an array.

const MongoClient = require('mongodb').MongoClient;
const credentials = require("../credentials.js");

const dbUrl = 'mongodb://' + credentials.username +
    ':' + credentials.password + '@' + credentials.host + ':' + credentials.port + '/' + credentials.database;

MongoClient.connect(dbUrl, (err, client) => {
    if (err) throw err;
    console.log('Successfully connected');

    let collection = client.db(credentials.database).collection('products');

    collection.find({}).toArray((err, docs) => {
        console.log(docs);
        client.close();
    });
});

here's the credentials.js file for the MongoDB connection

module.exports = {
    host:     'localhost',
    port:       '27017',
    username: 'user',
    password: 'secret',
    database: 'your_db'
}
random_user_0891
  • 1,863
  • 3
  • 15
  • 39