Hossein Zare
Hossein Zare

Reputation: 580

How to wait for new data from MongoDB in NodeJS?

I'm working on a chat project, NodeJS has to wait 25 secs for new data from MongoDB, any alternatives?

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

UPDATE:

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);

Upvotes: 0

Views: 636

Answers (1)

Jasper Bernales
Jasper Bernales

Reputation: 1681

take a look at changeStream

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

Upvotes: 2

Related Questions