Il metodo cursor.forEach() di MongoDB scorre un cursore e applica una funzione JavaScript function a ciascun documento che incontra.
Sintassi
La forma generale è:
db.collection.find().forEach(<function>)Qui collection indica la collezione che contiene i documenti.
La <function> accetta un solo argomento, che riceve il documento corrente in elaborazione.
Esempio
Supponiamo di avere una collezione chiamata products con tre documenti:
{ "_id" : 1, "product" : "Left Handed Screwdriver" } { "_id" : 2, "product" : "Left Blinker" } { "_id" : 3, "product" : "Long Weight" }Combinando forEach() con find(), puoi scorrere i documenti ed eseguire una funzione JavaScript su ciascuno.
Esempio:
db.products.find().forEach( function(p) { print( p.product.replace("Left","Right") ); } );Risultato:
Right Handed Screwdriver Right Blinker Long Weight
E se compare un errore?
Se vedi qualcosa del tipo:
uncaught exception: TypeError: db.products.findOne(...).forEach is not a function : @(shell):1:1
Controlla di usare find() e non findOne().
Il metodo findOne() restituisce un documento vero e proprio, non un cursore, quindi forEach() non funziona con esso. Inoltre, findOne() restituisce un solo documento: non ci sarebbe comunque nulla su cui iterare.