codefire
codefire

Reputation: 391

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:[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 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);});        
};

Upvotes: 1

Views: 5915

Answers (5)

random_user_0891
random_user_0891

Reputation: 2061

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'
}

Upvotes: 0

koti bajjuri
koti bajjuri

Reputation: 81

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();
        }
    );

});

Upvotes: 0

Deepika Chalpe
Deepika Chalpe

Reputation: 404

this is how we connect to our MongoDB server:

//app.js
var databaseUrl = "mydb"; // "username:[email protected]/mydb"
var collections = ["users"]
var db = require("mongojs").connect(databaseUrl, collections);



 db.users.find({email: "[email protected]"}, function(err, users) {
  if( err || !users) console.log("No female users found");
  else users.forEach( function(femaleUser) {
    console.log(femaleUser);
  } );
});

Upvotes: 1

codefire
codefire

Reputation: 391

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.

Upvotes: 0

Adlen Afane
Adlen Afane

Reputation: 1542

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)
}

Upvotes: 1

Related Questions