简体   繁体   中英

Access document of mongodb in javascript using node.js

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM