如何检查对猫鼬文档对象的数据库更改?

时间:2020-11-11 00:12:35

标签: node.js mongodb mongoose

想象一下,如下处理订单:

Order.find({_id: '5faae1245e387720f4a4ef3a'})
    .then(async order => {
        const products = order.products; //array of products
        for(let index = 0; index < products.length; index++){
            const if_success = await processProduct(products[index]);
            //Do something based on if_success
            /* ... */
        }
    })
    .catch()

订单上可能有很多产品,for循环必须顺序处理所有产品,这可能需要一段时间。诀窍是,尽管for循环在不了解周围环境的情况下运行得非常愉快,但用户可以通过其Web门户更改顺序5faae1245e387720f4a4ef3a,在这种情况下,我想中断循环。

我当然可以通过在循环的每次迭代中运行查询来检查订单是否有待处理的更改来实现此目的,但是我不愿意这样做,因为我不想在那里敲打那些查询的数据库可能有许多这样的循环以不同的顺序并行运行。

另一个非常相似的解决方案是,每循环x次迭代,向数据库查询未决的更改。 if(index % x === 0)种类的东西。

后者是我目前倾向于的目标,但也许我缺少一些东西。

我觉得猫鼬可以在这里帮助我,所以从概念上讲,我正在努力做到这一点:

Order.find({_id: '5faae1245e387720f4a4ef3a'})
    .then(async order => {
        const products = order.products; //array of products
        for(let index = 0; index < products.length; index++){
            const if_success = await processProduct(products[index]);
            //Do something based on if_success
            /* ... */
            if(order.metadata.ifDocChanged)
                break;
        }
    })
    .catch()

有没有办法对猫鼬做类似的事情?

0 个答案:

没有答案