0

I'm trying to connect to a mongoDB DB, and make some processes on a collection, and close the collection when all the collection items were processed. when I'm trying to receive array.length, I get undefined.

Db = require('mongodb').Db;
Server = require('mongodb').Server;
const db = new Db(DB_NAME, new Server(HOST, PORT));
// connect to mongoDB
db.open(function (err, db) {
  const Collection = db.collection(COLLECTION_NAME);
  var items = Collection.find({});
  var itemsLength = items.lebgth;
  var itemsProcessed = 0;
  items.forEach((item, index, array) => {
    // some process like:
    Collection.update({query}, {set}, callback)
    itemsProcessed++;
    if(itemsProcessed == array.length){
      db.close();
      // close connection if all items were processed
    }
  });
});

Is there any other way to do it?

2
  • 1
    Typo in items.lebgth. Commented Dec 15, 2016 at 9:25
  • items is cursor so you need to execute like: var items = Collection.find({}).toArray(); Commented Dec 15, 2016 at 9:45

3 Answers 3

2

Just use db.collection.count()

Sign up to request clarification or add additional context in comments.

Comments

1

EDIT:

You can use the optional callback of forEach, as documented here:

items.forEach((item) => {
    // some process...
}, (err) => db.close()); // close connection if all items were processed

4 Comments

in this case items.hasNext() is a promise object. how can I do somthing like this: items.hasNext((has) => { if(!has) db.close(); } );
it works just partly, the callback raised up before processing all elements.
Sounds weird. Are you doing anything asynchronous inside the loop?
Well, that was an important bit of information to mention in the original question... I suggest that in the forEach loop you'd build the update query (that way it can be a single update with multi=true instead of many update calls), call update in the forEach callback, and call db.close in the update callback. In addition, I suggest you'd edit your question and its title to better reflect what you're trying to do.
0

check this!

Collection.stat()

Comments

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.