0

I am trying to access my mongodb database document in my javascript function, I am able to access document using commond prompt . My requirement is to do same thing in java script function

db.products.find()[34];

This will return me something like this

{
        "_id" : ObjectId("5523c16d460df2542b8b56f4"),
        "refProductId" : 75,
        "name" : "3g%qg3O2Rd",
        "SKUType" : ")pvvrYhebP",
        "category" : "&aX96[u0Rn",
        "subCat" : "Piutu Pike",
        "price" : 175.6979,
        "pkgType" : "q)Hr$(K*07",
        "expDate" : ISODate("2015-06-22T05:59:17.844Z"),
        "manfacDate" : ISODate("2015-11-19T04:30:58.347Z"),
        "productSince" : ISODate("1989-11-24T07:29:28.753Z"),
        "pkgLastChangedDate" : ISODate("2015-06-19T22:52:24.136Z"),
        "mfId" : null
}

I want to achieve samething in my java function . But I am getting always undefined ( I tied all ways after googling the query )

Here is one such my javascript code

 // Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    console.log("Connected correctly to server");
    var prodtcol=db.collection('products');  
    var prodtcol=db.collection('products');  
    console.log(prodtcol.find()[3]);
    });

And this I am running on node.js

1 Answer 1

3

Try this instead:

MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    console.log("Connected correctly to server");
    var prodtcol=db.collection('products');  
    prodtcol.find(function(err, products){
        // products is an array of products.
        console.log(products); // Log all
        console.log(products[3]); // Log the 4th product, where 0 is the first.
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Richard , I tried this .. I am getting undefined something like this js-bson: Failed to load c++ bson extension, using pure JS version Connected correctly to server undefined
Something maybe wrong with your mongodb install, maybe try to reinstall latest version. This may be related stackoverflow.com/questions/21656420/…

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.