nedb icon indicating copy to clipboard operation
nedb copied to clipboard

Insert doesn't take place immediately

Open teoring opened this issue 3 years ago • 2 comments

I was trying to find any existing issue and went through the documentation but didn't manage to figure out what is wrong. In my case I am inserting elements in the database in the callback of the find function that is called in the loop. Here is the code snippet:


for( var i = 0; i < houses.addresses.length; i++ ) {
     let house = {
         address: addresses[i]
     };
     
    await db.houses.find( { address: house.address }, async function( err, docs ) {
        if( docs.length != 0 ) {
            return; 
        }
        
        await db.houses.insert( house, function ( error, newDoc ) {
            if( error ) {
                logger.error('Cant save the document: ' + JSON.stringify( doc ) + '. Caused by: ' + error );
            }
        });
        

So I am trying to find an entry, if entry doesn't exist I insert the entry. But for some reason I end up inserting many entries:

{"address":"Vaartsestraat 0 ong","_id":"x5BtMrYmkiv2tOhy"} {"address":"Vaartsestraat 0 ong","_id":"hms08wtX7yAEFpX3"} {"address":"Vaartsestraat 0 ong","_id":"OjW99USIFU3adzoo"} .....

Any idea why this might be happening?

teoring avatar Aug 17 '21 17:08 teoring

I am using "nedb": "^1.8.0" version from npm.

teoring avatar Aug 18 '21 07:08 teoring

you should use Promise API to wrap callback function

program-spiritual avatar Sep 02 '21 02:09 program-spiritual