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.