Mongoose Insert Subdocument on specific location

JS
S
JavaScript

Guide for inserting subdocuments at specific locations within MongoDB documents using Mongoose ODM. Covers array manipulation and positional updates.

1    const [updatedSlotError, updatedSlot] = await SafeAwait(
2      TreeModel.update(
3        { _id: tree._id },
4        {
5          $push: {
6            'children.$[i].events': newEvent,
7          },
8          $set: {
9            'children.$[i].surveys': normalizedSurveys,
10            'children.$[i].editedBy': request ? request.user.id : undefined,
11          },
12        },
13        {
14          arrayFilters: [
15            {
16              'i._id': ObjectId(myBranchId),
17            },
18          ],
19        }
20      )
21    );
22
23
24
25// Update multiple positions
26return TranslationModel.updateOne(
27  { _id: slot._id },
28  {
29    $push: {
30      'comments.$[i].comments.$[t].comments': newComment,
31    },
32  },
33  {
34    arrayFilters: [
35      {
36        'i._id': comment._id,
37      },
38      {
39        't.commentId': commentId,
40      },
41    ],
42  }
43);

Created on 9/30/2020