0

I'm building an app in Node/Express/MongoDB with Mongoskin. In this app, there is a scheduled function, that runs at the beginning of every month.

This function consist of the following code:

clients.find({}, {cost: 1, invoices: 1 }).toArray(function(err, dbDocs) {
  if (err) throw err; 

  // Set up a current time variable and a general populated invoice object.
  var currentTime = new Date();
  var invoice = {
    year: currentTime.getFullYear(), 
    quarter: Math.floor(currentTime.getMonth() / 3) + 1, 
    paid: false
  };

  // Loop trough the fetched documents.
  for (var i = 0, j = dbDocs.length; i < j; i += 1) { 
    invoice.quarterCost = (dbDocs[i].cost.monthly * 3);

    clients.update({_id:dbDocs[i]._id}, {$push:{ invoices: invoice }}, function(err, result) {
      if (err) throw err; 

      console.log('LogCost created new client invoice')
    ));
  }
});

This function first query all available client documents from the Database, then use this data to make a a new invoice object for every client, and the push this invoice to the clients array of invoices, and save this to the database.

Right now i have my updates in a loop, which means there will be many single update queries when there are many clients to update. I would not expect more than maybe 100-200 clients.

Question: Is there a better way to structure this function and it's update query? What troubles me is the single document update query in a loop... but maybe this is the right way to do it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Anders Östman
  • 3,702
  • 4
  • 26
  • 48
  • 1
    This seems fine for something that is run once a month with so few documents. Unless you've got a specific performance issue, this seems like premature optimization. – WiredPrairie Nov 19 '13 at 11:48
  • Ok, but **if** I would like to optimize this. How would I principially do it? – Anders Östman Nov 19 '13 at 12:39
  • 1
    optimize it how? Would you like to sacrifice reliability, write guarantees, etc? The type of update you're doing requires individual calls to `update` as you've seen. – WiredPrairie Nov 19 '13 at 12:59
  • The subject of several individual calls is the core of my question. Is there a way to make this update with just **one** mongoDB call, maybe submit some kind of array with several invoice object to add to several different client document. But this does not seems to be possible. – Anders Östman Nov 19 '13 at 13:28
  • 1
    As I said, the type of update you're performing requires individual calls. – WiredPrairie Nov 19 '13 at 13:31

0 Answers0