如何在NodeJS中等待来自MongoDB的新数据?

时间:2019-08-27 09:04:49

标签: node.js mongodb express

我正在处理一个聊天项目,NodeJS必须等待25秒才能从MongoDB获得新数据,我可以在While循环中实现它,我想听听其他人的建议。

while(true) {
    db.messages.find({
    ...
    }).then(result) => {
        if (result.length > 0) {
            return result;
        }
    })
}

顺便说一句,我的方法不好吗?

更新:

另一种方式...

let secs = 0;
const iv = setInterval(() => {
        secs++;

        db.messages.find({
        ...
        }).then(result) => {
            if (result.length > 0) {
                clearInterval(iv);

                res.json(result);
                return;
            }
        });

        if (secs === 25)
           clearInterval(iv);
}, 1000);

1 个答案:

答案 0 :(得分:1)

看看changeStream

const collection = db.collection('messages');
const changeStream = collection.watch();
changeStream.on('change', next => {
  // process next document
});