Insertion in mongo forEach continues forever

I create fake documents by "expanding" existing documents 20 times. But; the forEach loop never ends. Why?

db['COLLECTION'].find({}).forEach(function(doc){
    for( var x = 0; x < 20; x++ ) {
            delete doc['_id'];
            doc['Author'] = randArrayElement(names); /* chooses random name */
            doc['Description'] = buzzword(); /* makes something up*/

            db['COLLECTION'].insert(doc);
        }
    }
 )

      

+3


source to share


1 answer


I think you need to use snapshot here:

db['COLLECTION'].find().snapshot().forEach(function(doc){
  ...
})

      

My guess is that this is because write operations might move the document, and the snapshot fixes it:



The $ snapshot statement prevents the cursor from returning the document more than once, because an intermediate write operation causes the document to move.

If that doesn't help, then I have another idea that new documents will be raised with the cursor. To overcome this, I would create an array of all documents and then list them separately and do your 20 inserts for each one.

+5


source







All Articles