Skip to content

Commit d9b8456

Browse files
authored
DOCSP-26238: create keys from variables (#469)
* DOCSP-26238: creating keys from variables * clarify wording * MW PR fixes 1 * period fix
1 parent b5bd9ae commit d9b8456

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

source/fundamentals/typescript.txt

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ You can find a code snippet that shows how to specify a type for the ``FindCurso
8484
class in the
8585
:ref:`Find Multiple Documents Usage Example <node-driver-find-usage-example-code-snippet>`.
8686

87-
8887
Type Safety and Dot Notation
8988
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9089

@@ -122,6 +121,46 @@ The type error raised by the preceding code snippet is as follows:
122121
...
123122
Type '"Sylvilagus"' is not assignable to type 'Condition<"Canis" | "Felis">'.
124123

124+
Referencing Keys that Incorporate Variables
125+
```````````````````````````````````````````
126+
127+
If you need to query a collection or perform another operation with a
128+
key that incorporates variables, you must use an ``as const``
129+
assertion when specifying the key. This mechanism allows your
130+
code to compile successfully as long as the input types are correct.
131+
132+
The following code snippet defines the ``ClassificationPet`` interface
133+
and the ``Mealtime`` interface. ``ClassificationPet`` includes a
134+
``mealtimes`` field that contains an array of ``Mealtime`` interfaces,
135+
each of which includes a ``time`` field:
136+
137+
.. code-block:: typescript
138+
139+
interface ClassificationPet {
140+
name: string;
141+
mealtimes: Mealtime[];
142+
}
143+
144+
interface Mealtime{
145+
time: string;
146+
amount: number;
147+
}
148+
149+
The following code snippet performs a find-and-update operation on a
150+
collection of ``ClassificationPet`` documents. The operation
151+
updates the nested ``time`` field of the ``Mealtime`` instance at index
152+
``1``. The index position is specified by the variable ``mealCounter``:
153+
154+
.. code-block:: typescript
155+
:emphasize-lines: 5
156+
157+
const mealCounter = 1;
158+
159+
await collection.findOneAndUpdate(
160+
{ name: "Lassie" },
161+
{ $set: { [`mealtimes.${mealCounter}.time` as const]: '4:00 PM' } },
162+
);
163+
125164
To learn more about dot notation, see
126165
:manual:`Dot Notation </core/document/#dot-notation>`
127166
in the MongoDB manual.

0 commit comments

Comments
 (0)