2

Relevant packages:

"dependencies": {
  "mongodb":    "1.4.x",
  "bluebird":   "2.3.x"
}

I've looked at:

I'm stuck after the findAsync({}).

I'd prefer a cursor, but it's rare I'd have too much to call toArray().

It's also possible I'm doing this completely wrong.

MongoClient.connectAsync('mongodb://127.0.0.1:27017/sr')
  .then(function(_db) {
    db = _db;
    return db.collectionAsync('posts');
  })
  .then(function(colPosts) {
    return colPosts.findAsync({});
  })
  .then ( A MIRACLE OCCURS )
  .catch(function(e) {
    console.log(e);
  })
  .finally(function() {
    if (db) db.close();
  });

Where the miracle occurs I want to either iterate over the cursor results or the arrayified collection. I'm having problems figuring out how to go about this.

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302

1 Answers1

1

As I understand it, .findAsync returns a promise for a cursor. If you want to pull the data into memory (as with .toArray) I think what you're looking for is something like:

MongoClient.connectAsync('mongodb://127.0.0.1:27017/sr')
  .then(function(_db) {
    db = _db;

    return db
      .collection('posts')
      .find({})
      .limit(limit)
      .sort(sort)
      .toArrayAsync();
  })
  .then(function(posts) {
    console.log('posts', posts);
  })
  .catch(function(e) {
    console.log(e);
  });
kurttheviking
  • 615
  • 1
  • 7
  • 21