0

I'm pretty new in Node.js and I have this project. Basically I have some data sits in a mongoDB collection("data") and I'm trying to get that data and display it on the browser.

Here is what I've got so far;

    var MongoClient = require('mongodb').MongoClient
        ,format = require('util').format;
    var sys = require ("sys");
    my_http = require("http");

      my_http.createServer(function(request, response){
         sys.puts("Touched !!");
         response.writeHeader(200, {"Content-Type": "text/plain"});
         response.write(extractData()).toString();
         response.end();
     }).listen(8080);
sys.puts("Server is running on 8080"); // Server kicks in...np

function extractData(){

    MongoClient.connect('mongodb://127.0.0.1:27017/mongoDB', function(err, db){
        if (err){
            console.log("Can't Connect to DB !!");
        }else {
            console.log("Connected to DB !!");   // connects to DB, np
            db.data.find({}, function(err, data){  // .find is the problem
                if (err || !data) console.log("No Data Found");
                else data.forEach(function (data){
                    console.log(data);
                });
            }).toArray();
        }
    });
}

And after I run "node server.js" and refresh the already open localhost:8080, I get this;

Server is running on 8080
Touched !!
Touched !!
Connected to DB !!

d:\Projects\SCRIPTS\mdp.scripts.testing-tools\jsFinderWmongoDB\node_modules\mongodb\lib\mongodb\mongo_client.js:475
          throw err
                ^
TypeError: Cannot call method 'find' of undefined
    at d:\Projects\SCRIPTS\mdp.scripts.testing-tools\jsFinderWmongoDB\server.js:21:21
    at d:\Projects\SCRIPTS\mdp.scripts.testing-tools\jsFinderWmongoDB\node_modules\mongodb\lib\mongodb\mongo_client.js:4
72:11
    at process._tickCallback (node.js:415:13)

Don't understand why there is a problem with .find() and of course can't display any data...

Any ideas?

Edit:

Well, we are certainly getting somewhere. I've made some changes.

Current code:

function extractData(){

MongoClient.connect('mongodb://127.0.0.1:27017/mongoDB', function(err, db){
        if (err){
            console.log("Can't Connect to DB !!");
        }else {
            sys.puts("Connected to DB !!");   // connects to DB, np
            db.collection('data').find({}, function(err, data){  
                if (err || !data) console.log("No Data Found");
                //else db.collection('data').forEach(function (data){
                //    console.log(data);
                //});
            });//.toArray();
        }
    });
}

Browser response is "undefined"

I'm guessing "extractData" function is NOT returning something legit. Therefore the collection set "data" is returning empty.

And yes I've checked one more time, I have data in the dataset.

2
  • 1
    so db.data is undefined, are you sure you don't want db.collection('data') or something like that ? Commented Feb 27, 2015 at 17:05
  • Well, we are certainly getting somewhere. I've made some changes. Commented Feb 27, 2015 at 17:52

2 Answers 2

1

You need to set a collection to use before you can do anything with it.

var collection = db.collection('data');
collection.find({},function(err,data){
    console.log(data);
});

Would be how you do it.

Update ** This was how I did my first mongoDB stuff using express Might help you.

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');

app.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
 collection.find({},{},function(e,docs){
    res.render('userlist', {
        "userlist" : docs
    });
 });
});
Sign up to request clarification or add additional context in comments.

1 Comment

That worked, thank you. But the browser still displaying "undefined".
0

I get the details about the stored data when do console.log(data);

Here is a glimpse of it

Server is running on 8080
Touched !!
Connected to DB !!
{ db: 
   { domain: null,
     _events: {},
     _maxListeners: 10,
     databaseName: 'mongoDB',
     serverConfig: 
      { domain: null,
        _events: {},
        _maxListeners: 10,
        auth: [Getter],
        _callBackStore: [Object],
        _commandsStore: [Object],
        _dbStore: [Object],
        host: '127.0.0.1',
        port: 27017,
        options: [Object],
        internalMaster: true,
        connected: true,
        poolSize: 5,
        disableDriverBSONSizeCheck: false,
        _used: true,
        replicasetInstance: null,
        emitOpen: false,
        ssl: false,
        sslValidate: false,
        sslCA: null,
        sslCert: undefined,
        sslKey: undefined,
        sslPass: undefined,
        serverCapabilities: [Object],
        name: '127.0.0.1:27017',
        socketOptions: [Object],
        logger: [Object],
        eventHandlers: [Object],
        _serverState: 'connected',
        _state: [Object],
        recordQueryStats: false,
        socketTimeoutMS: [Getter/Setter],
        _readPreference: [Object],
        db: [Circular],
        dbInstances: [Object],
        connectionPool: [Object],
        isMasterDoc: [Object] },
     options: 
      { read_preference_tags: null,
        read_preference: 'primary',
        url: 'mongodb://127.0.0.1:27017/mongoDB',
        native_parser: true,
        readPreference: [Object],
        safe: false,
        w: 1 },
     _applicationClosed: false,
     slaveOk: false,
     bufferMaxEntries: -1,
     native_parser: true,
     bsonLib: 
      { BSON: [Object],
        Long: [Object],
        ObjectID: [Object],
        DBRef: [Object],
        Code: [Object],
        Timestamp: [Object],
        Binary: [Object],
        Double: [Object],
        MaxKey: [Object],
        MinKey: [Object],
        Symbol: [Object] },
     bson: { promoteLongs: true },
     bson_deserializer: 
      { Code: [Object],
        Symbol: [Object],
        BSON: [Object],
        DBRef: [Object],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Object],
        MinKey: [Object],
        MaxKey: [Object],
        promoteLongs: true },
     bson_serializer: 
      { Code: [Object],
        Symbol: [Object],
        BSON: [Object],
        DBRef: [Object],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Object],
        MinKey: [Object],
        MaxKey: [Object],
        promoteLongs: true },
     _state: 'connected',
     pkFactory: 
      { [Function: ObjectID]
        index: 16043018,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid],
        ObjectID: [Circular],
        ObjectId: [Circular] },
     forceServerObjectId: false,
     safe: false,
     notReplied: {},
     isInitializing: true,
     openCalled: true,
     commands: [],
     logger: { error: [Function], log: [Function], debug: [Function] },
     tag: 1425061857066,
     eventHandlers: 
      { error: [],
        parseError: [],
        poolReady: [],
        message: [],
        close: [] },
     serializeFunctions: false,
     raw: false,
     recordQueryStats: false,
     retryMiliSeconds: 1000,
     numberOfRetries: 60,
     readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
  collection:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.