0

I'm trying to connecto to a mongoDB and count for all documents of an article:

var MongoClient = require('mongodb').MongoClient
var mongoUrl = 'mongodb://localhost:27017/test'

MongoClient.connect(mongoUrl, function (err, db) {
  if (!err) console.log('Connected successfully to server: ' + mongoUrl)
  var articles = db.collection('articles')
  console.log(articles.count())
  db.close()
})

But I do get the output Promise { <pending> } instead of a number.

user3142695
  • 15,844
  • 47
  • 176
  • 332
  • Thats why count is an async operation, handle the promise using [then](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) – Vanojx1 Jul 17 '17 at 09:56

1 Answers1

1
db.collection('articles').count()

this line return promise as pointed in documentation. You need to handle this promise properly to get article count (it's a asynchronous operation so you need to wait unknown time for query result)
you need to do something like this

db.collection('articles').count().then(function(result){
  console.log(result)
 }, function(err){
   return console.log(err);
 });
cymruu
  • 2,808
  • 2
  • 11
  • 23