Iterate over changing database in endless loop

Im working this piece of code written in NodeJS which basically updates a database of Fqdn with corresponding IPs every 5 seconds ( 1 entry at a time). However it would be great if I could just use the cursor to retrieve the current element, so i do not have to run a query on matching names. I did not found much on cursors in the mongoose docs, is there a way to do this?

DatabaseHandler.resolveFqdns = function () {
    let cursor = Fqdn.find({ }).cursor();
    setInterval( function () {
        cursor.next(function(error, doc) {
            if(doc){
                debug(doc);
                dns.resolve4(doc.url, (err, addresses) => {
                    if (err) throw err;
                    debug(`addresses: ${JSON.stringify(addresses)}`);

                    // TODO get Element the cursor points to

                    addresses.forEach((a) => {


             // TODO modify element
                });

                // TODO update elementto db
            });
        }else{
            cursor = Fqdn.find({ }).cursor();
        }
    });
}, 5000);

}

Answer

The doc object in the cursor’s callback is a Mongoose document object. From the docs http://mongoosejs.com/docs/documents.html:

Mongoose documents represent a one-to-one mapping to documents as stored in MongoDB. Each document is an instance of its Model.

Hence, you can use the set and save methods.

DatabaseHandler.resolveFqdns = function () {
    let cursor = Fqdn.find().cursor();
    setInterval(function () {
        cursor.next(function(error, doc) {
            if(doc){
                debug(doc);
                dns.resolve4(doc.url, (err, addresses) => {
                    if (err) throw err;
                    debug(`addresses: ${JSON.stringify(addresses)}`);

                    // update the document
                    doc.set('addresses', addresses);

                    // save changes
                    doc.save();
                });
            } else {
                cursor = Fqdn.find().cursor();
            }
        });
    }, 5000);
}

Instead of doc.set(), you can use doc.addresses = addresses as well since they have the same effect. From the docs http://mongoosejs.com/docs/documents.html:

You can also use .set() to modify documents. Under the hood, tank.size = ‘large’; becomes tank.set({ size: ‘large’ }).

Leave a Reply

Your email address will not be published. Required fields are marked *