Skip to content

Commit d46e630

Browse files
committed
DOCSP-29345 - Replace forEach (#671)
* replace forEach * js feedback (cherry picked from commit 0b7bd5f)
1 parent dea2807 commit d46e630

File tree

17 files changed

+128
-87
lines changed

17 files changed

+128
-87
lines changed

source/code-snippets/crud/cursor.js

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,6 @@ const uri =
66
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
77
const client = new MongoClient(uri);
88

9-
async function forEachIteration(myColl) {
10-
// start foreach cursor example
11-
const cursor = myColl.find({});
12-
await cursor.forEach(doc => console.log(doc));
13-
// end foreach cursor example
14-
console.log(await myColl.countDocuments());
15-
}
16-
179
async function asyncIteration(myColl) {
1810
// start async cursor example
1911
const cursor = myColl.find({});
@@ -81,7 +73,6 @@ async function run() {
8173
const database = client.db("test");
8274
const orders = database.collection("orders");
8375

84-
await forEachIteration(orders);
8576
await asyncIteration(orders);
8677
await manualIteration(orders);
8778
await streamAPI(orders);

source/code-snippets/crud/startrek.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ async function word(movies) {
2323
if ((await movies.countDocuments(query)) === 0) {
2424
console.log("No documents found!");
2525
}
26-
await cursor.forEach(console.dir);
26+
for await (const doc of cursor) {
27+
console.dir(doc);
28+
}
2729
}
2830

2931
async function phrase(movies) {
@@ -44,7 +46,9 @@ async function phrase(movies) {
4446
if ((await movies.countDocuments(query)) === 0) {
4547
console.log("No documents found!");
4648
}
47-
await cursor.forEach(console.dir);
49+
for await (const doc of cursor) {
50+
console.dir(doc);
51+
}
4852
}
4953

5054
async function negation(movies) {
@@ -65,7 +69,9 @@ async function negation(movies) {
6569
if ((await movies.countDocuments(query)) === 0) {
6670
console.log("No documents found!");
6771
}
68-
await cursor.forEach(console.dir);
72+
for await (const doc of cursor) {
73+
console.dir(doc);
74+
}
6975
}
7076

7177
async function relevance(movies) {
@@ -92,7 +98,9 @@ async function relevance(movies) {
9298
if ((await movies.countDocuments(query)) === 0) {
9399
console.log("No documents found!");
94100
}
95-
await cursor.forEach(console.dir);
101+
for await (const doc of cursor) {
102+
console.dir(doc);
103+
}
96104
}
97105

98106
async function run() {

source/code-snippets/crud/theaters.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ async function proximity(theaters) {
2424
if ((await theaters.countDocuments(query)) === 0) {
2525
console.log("No documents found!");
2626
}
27-
await cursor.forEach(console.dir);
27+
for await (const doc of cursor) {
28+
console.dir(doc);
29+
}
2830
}
2931

3032
async function range(theaters) {
@@ -55,7 +57,9 @@ async function range(theaters) {
5557
if ((await theaters.countDocuments(query)) === 0) {
5658
console.log("No documents found!");
5759
}
58-
await cursor.forEach(console.dir);
60+
for await (const doc of cursor) {
61+
console.dir(doc);
62+
}
5963
}
6064

6165
async function run() {

source/code-snippets/quick-reference.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@ async function query(coll) {
1616
async function queryMany(coll) {
1717
console.log("find");
1818
const cursor = coll.find({ year: 2005 });
19-
await cursor.forEach(console.dir);
19+
for await (const doc of cursor) {
20+
console.dir(doc);
21+
}
2022
}
2123

2224
async function insertOne(coll) {
@@ -108,7 +110,9 @@ async function watchStart(coll) {
108110

109111
async function accessCursorIterative(coll) {
110112
const cursor = coll.find().limit(10);
111-
await cursor.forEach(console.dir);
113+
for await (const doc of cursor) {
114+
console.dir(doc);
115+
}
112116
}
113117

114118
async function accessCursorArray(coll) {
@@ -134,17 +138,23 @@ async function skipExample(coll) {
134138

135139
async function sortExample(coll) {
136140
const cursor = coll.find().limit(50).sort({ year: 1});
137-
await cursor.forEach(console.dir);
141+
for await (const doc of cursor) {
142+
console.dir(doc);
143+
}
138144
}
139145

140146
async function projectExample(coll) {
141147
const cursor = coll.find().project({ _id: 0, year: 1, imdb: 1 });
142-
await cursor.forEach(console.dir);
148+
for await (const doc of cursor) {
149+
console.dir(doc);
150+
}
143151
}
144152

145153
async function searchText(coll) {
146154
const result = coll.find({$text: { $search: 'zissou' }}).limit(30).project({title: 1});
147-
await result.forEach(console.dir);
155+
for await (const doc of cursor) {
156+
console.dir(doc);
157+
}
148158
}
149159

150160
async function distinct(coll) {

source/code-snippets/usage-examples/find.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@ async function run() {
2727
console.log("No documents found!");
2828
}
2929

30-
// replace console.dir with your callback to access individual elements
31-
await cursor.forEach(console.dir);
30+
for await (const doc of cursor) {
31+
console.dir(doc);
32+
}
33+
3234
} finally {
3335
await client.close();
3436
}

source/code-snippets/usage-examples/find.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ async function run() {
3737
console.warn("No documents found!");
3838
}
3939

40-
await cursor.forEach(console.dir);
40+
for await (const doc of cursor) {
41+
console.dir(doc);
42+
}
4143
} finally {
4244
await client.close();
4345
}

source/fundamentals/crud/query-document.txt

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,9 @@ documents containing a field called "name" that has a value of "apples":
6666

6767
const query = { "name": "apples" };
6868
const cursor = myColl.find(query);
69-
await cursor.forEach(console.dir);
69+
for await (const doc of cursor) {
70+
console.dir(doc);
71+
}
7072

7173
This code snippet returns the following results:
7274

@@ -107,7 +109,9 @@ value greater than 5 and prints them out:
107109
// $gt means "greater than"
108110
const query = { qty: { $gt : 5 } };
109111
const cursor = myColl.find(query);
110-
await cursor.forEach(console.dir);
112+
for await (const doc of cursor) {
113+
console.dir(doc);
114+
}
111115

112116
This code snippet returns the following results:
113117

@@ -131,7 +135,9 @@ that is not greater than 5 and prints them out:
131135

132136
const query = { qty: { $not: { $gt: 5 }}};
133137
const cursor = myColl.find(query);
134-
await cursor.forEach(console.dir);
138+
for await (const doc of cursor) {
139+
console.dir(doc);
140+
}
135141

136142
This code snippet returns the following results:
137143

@@ -179,7 +185,9 @@ field:
179185

180186
const query = { microsieverts: { $exists: true } };
181187
const cursor = myColl.find(query);
182-
await cursor.forEach(console.dir);
188+
for await (const doc of cursor) {
189+
console.dir(doc);
190+
}
183191

184192
This code snippet returns the following results:
185193

@@ -206,7 +214,9 @@ a remainder of 0:
206214
// $mod means "modulo" and returns the remainder after division
207215
const query = { qty: { $mod: [ 3, 0 ] } };
208216
const cursor = myColl.find(query);
209-
await cursor.forEach(console.dir);
217+
for await (const doc of cursor) {
218+
console.dir(doc);
219+
}
210220

211221
This code snippet returns the following results:
212222

source/fundamentals/crud/read-operations/cursor.txt

Lines changed: 19 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ pulling all matching documents into a collection in process memory.
5151
.. warning::
5252

5353
Do not combine different cursor paradigms on a single cursor.
54-
Operations such as ``hasNext()``, ``forEach()``, and ``toArray()``
54+
Operations such as ``hasNext()`` and ``toArray()``
5555
each predictably modify the original cursor. If you mix these calls
5656
on a single cursor, you may receive unexpected results.
5757

@@ -68,44 +68,14 @@ pulling all matching documents into a collection in process memory.
6868
fetch, the cursor is exhausted which means it ceases to respond to methods
6969
that access the results.
7070

71-
.. _node-fundamentals-cursor-foreach:
72-
73-
For Each Functional Iteration
74-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
75-
76-
You can pass a function to the `forEach() <{+api+}/classes/FindCursor.html#forEach>`__ method of any cursor to iterate through
77-
results in a functional style:
78-
79-
.. literalinclude:: /code-snippets/crud/cursor.js
80-
:language: javascript
81-
:start-after: start foreach cursor example
82-
:end-before: end foreach cursor example
83-
84-
.. _node-fundamentals-cursor-array:
85-
86-
Return an Array of All Documents
87-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
88-
89-
For use cases that require all documents matched by a query to be held
90-
in memory at the same time, use `toArray() <{+api+}/classes/FindCursor.html#toArray>`__.
91-
Note that large numbers of matched documents can cause performance issues
92-
or failures if the operation exceeds memory constraints. Consider using
93-
`forEach() <{+api+}/classes/FindCursor.html#forEach>`__ to iterate
94-
through results unless you want to return all documents at once.
95-
96-
.. literalinclude:: /code-snippets/crud/cursor.js
97-
:language: javascript
98-
:start-after: start fetchAll cursor example
99-
:end-before: end fetchAll cursor example
100-
10171
.. _node-fundamentals-async-iteration:
10272

10373
Asynchronous Iteration
10474
~~~~~~~~~~~~~~~~~~~~~~
10575

10676
Cursors implement the :mdn:`AsyncIterator
10777
<Web/JavaScript/Reference/Statements/for-await...of>` interface, which
108-
allows you to use cursors in ``for``...``await`` loops:
78+
allows you to use cursors in ``for await...of`` loops:
10979

11080
.. literalinclude:: /code-snippets/crud/cursor.js
11181
:language: javascript
@@ -125,6 +95,23 @@ method to retrieve the subsequent element of the cursor:
12595
:start-after: start manual cursor example
12696
:end-before: end manual cursor example
12797

98+
.. _node-fundamentals-cursor-array:
99+
100+
Return an Array of All Documents
101+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
102+
103+
For use cases that require all documents matched by a query to be held
104+
in memory at the same time, use the `toArray() <{+api+}/classes/FindCursor.html#toArray>`__
105+
method. Note that large numbers of matched documents can cause performance issues
106+
or failures if the operation exceeds memory constraints. Consider using
107+
the ``for await...of`` syntax to iterate
108+
through results rather than returning all documents at once.
109+
110+
.. literalinclude:: /code-snippets/crud/cursor.js
111+
:language: javascript
112+
:start-after: start fetchAll cursor example
113+
:end-before: end fetchAll cursor example
114+
128115
Stream API
129116
~~~~~~~~~~
130117

source/fundamentals/crud/read-operations/distinct.txt

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,9 @@ unique values of the ``borough`` field:
6767

6868
// specify "borough" as the field to return values for
6969
const cursor = myColl.distinct("borough");
70-
await cursor.forEach(console.dir);
70+
for await (const doc of cursor) {
71+
console.dir(doc);
72+
}
7173

7274
This code outputs the following ``borough`` values:
7375

@@ -98,7 +100,9 @@ excludes restaurants in "``Brooklyn``":
98100

99101
// find the filtered distinct values of "cuisine"
100102
const cursor = myColl.distinct("cuisine", query);
101-
await cursor.forEach(console.dir);
103+
for await (const doc of cursor) {
104+
console.dir(doc);
105+
}
102106

103107
In this case, the query filter matches every borough value except for "``Brooklyn``". This
104108
prevents ``distinct()`` from outputting one ``cuisine`` value, "``Middle Eastern``".
@@ -137,7 +141,9 @@ conventions when outputting the distinct ``restaurant`` values:
137141
const options = { collation: { locale: "de" }};
138142

139143
const cursor = myColl.distinct("restaurant", query, options);
140-
await cursor.forEach(console.dir);
144+
for await (const doc of cursor) {
145+
console.dir(doc);
146+
}
141147

142148
In this case, German string ordering conventions place words beginning with "Ä" before
143149
those beginning with "B". The code outputs the following:

source/fundamentals/crud/read-operations/limit.txt

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ snippet to insert documents that describe books into the
4242
{ "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 },
4343
{ "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 },
4444
{ "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 },
45-
{ "_id": 6, "name": "A Dance With Dragons", "author": "Tolkein", "length": 1104 },
45+
{ "_id": 6, "name": "A Dance With Dragons", "author": "Martin", "length": 1104 },
4646
]);
4747

4848
.. include:: /includes/access-cursor-note.rst
@@ -64,7 +64,9 @@ books, and applies a ``limit`` to return only ``3`` results:
6464
const sort = { length: -1 };
6565
const limit = 3;
6666
const cursor = myColl.find(query).sort(sort).limit(limit);
67-
await cursor.forEach(console.dir);
67+
for await (const doc of cursor) {
68+
console.dir;
69+
}
6870

6971
The code example above outputs the following three documents, sorted by
7072
length:
@@ -116,7 +118,9 @@ passing the number of documents to bypass as shown below:
116118
const limit = 3;
117119
const skip = 3;
118120
const cursor = myColl.find(query).sort(sort).limit(limit).skip(skip);
119-
await cursor.forEach(console.dir);
121+
for await (const doc of cursor) {
122+
console.dir;
123+
}
120124

121125
This operation returns the documents that describe the fourth through sixth
122126
books in order of longest-to-shortest length:

source/fundamentals/crud/read-operations/project.txt

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,9 @@ field of each document:
6666
// return only* the name field
6767
const projection = { name: 1 };
6868
const cursor = myColl.find().project(projection);
69-
await cursor.forEach(console.dir);
69+
for await (const doc of cursor) {
70+
console.dir(doc);
71+
}
7072

7173
The projection document specifies a value of ``1`` for ``name`` to
7274
indicate that the read operation result should *include* the ``name``
@@ -104,7 +106,9 @@ returned documents.
104106
// return only the name field
105107
const projection = { _id: 0, name: 1 };
106108
const cursor = myColl.find().project(projection);
107-
await cursor.forEach(console.dir);
109+
for await (const doc of cursor) {
110+
console.dir(doc);
111+
}
108112

109113
The projection document specifies a value of ``1`` for ``name`` to
110114
indicate that the read operation result should *include* the ``name``
@@ -132,7 +136,9 @@ order in which they are returned.
132136

133137
const projection = { _id: 0, rating: 1, name: 1 };
134138
const cursor = myColl.find().project(projection);
135-
await cursor.forEach(console.dir);
139+
for await (const doc of cursor) {
140+
console.dir(doc);
141+
}
136142

137143
This example that identifies two fields to include in the projection yields
138144
the following results:

0 commit comments

Comments
 (0)