我正在使用 Mongoskin 在 Node/Express/MongoDB 中构建一个应用程序。在这个应用程序中,有一个预定功能,在每个月初运行。
该函数由以下代码组成:
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')
));
}
});
该函数首先从数据库中查询所有可用的客户文档,然后使用这些数据为每个客户创建一个新的发票对象,并将此发票推送到客户发票数组中,并将其保存到数据库中。
现在我的更新是循环的,这意味着当有很多客户端要更新时,会有很多单个更新查询。我预计不会超过 100-200 个客户。
问题:有没有更好的方法来构造这个函数和它的更新查询?困扰我的是循环中的单个文档更新查询......但也许这是正确的方法。