与nodejs的async +递归+数据库更新操作

时间:2013-10-19 20:48:07

标签: algorithm node.js mongodb recursion mongoose

这是一个算法,它返回一个项目可以插入的位置(以回调的形式),并更新前一个项目的位置。

Put the item into infinite length array (assumed), 0<=index<INFINITY,
and for empty array largest_index_occupied = 0. ALSO largest_index_occupied is dynamically retrieved from database.(assumed). No two item can share same index. No item must be lost during any operation. indexes are in increasing order.



1. if index not provided OR index provided is greater than largest_index_occupied then put item at index : largest_index_occupied+5;
2. If index provided AND less than equals to largest_index_occupied, :
   a. if (No other item already exists at that index) : simply put the item at that index
   b. otherwise (means if a item already exists at that index) : increase the index of all items by one untill we get an empty index. and put the new item at the index actually passed by user(which must be empty now).

2.b示例:

说 - 显示空索引。

以前的州

0 - - - - 5 6 7 - - 10
a - - - - b c d - - e

输入索引:5,f

新州:

0 - - - - 5 6 7 8 - 10
a - - - - f b c d - e

Noe f的新索引是5。

我的要求是在nodejs中结合异步,递归和IO操作(db update - 在2.b的情况下为项目的索引)编写上述代码。

我期待next(err,indexToBeInserted);回调只有在完成所有更新后才能调用。

我的功能块在这里:

toInsert(mongooseModel,next,indexToBeInserted) {
 // async code goes here.
}

ps:如果您有更好的解决方案,请分享。

0 个答案:

没有答案