MongoDB - How can I get the size of a collection using Node.js? -
i'm writing server side code using node.js, i'm trying mongodb collection size using count method not working.
this code
var mongo = require('mongodb'); var host = "127.0.0.1"; var port = mongo.connection.default_port; function getstock(name, callback) { var db = new mongo.db("testdb", new mongo.server(host, port, {})); db.open (function(error){ console.log("we connected! " + host + ":" +port); db.collection("stocks", function(error, collection){ console.log("we have collection"); **var numofdocs = db.collection('stocks').count()** **console.log("the num of docs in our collection is: ",numofdocs)** collection.find({"name":name.tostring()}, function(error, cursor) { cursor.toarray(function(error, stocks) { if (stocks.length==0) { //console.log("no stocks found!"); callback(false); } else { callback(stocks[0]); //console.log("found stock -> ",stocks[0]); } }); }); }); }); }
.count() asynchronous function, .find() is.
try following code:
collection.count({}, function(error, numofdocs) { console.log('i have '+numofdocs+' documents in collection'); // .. }); the first argument .count() should search query. since want count documents, i'm passing empty object {} search query.
Comments
Post a Comment