title: Using $addFields as part of an update function in MongoDB
body: <p>I am trying to figure out how to use the <code>$addFields</code> operation within a function I'm using to update a document. The logic to generate this field is simple enough, I just pull out the last object in an array, like so:</p>
  
  <pre><code>  {
      $addFields: { activeWorkflow: { $arrayElemAt: ["$workflow", -1.0] } }
    }
  </code></pre>
  
  <p>Now I need to figure out how to get this aggregation into my update function, the relevant code of which looks like this:</p>
  
  <pre><code>updatedDoc = await request.findOneAndUpdate(
    StaffMember,
    {
      _id: request.parameters.id
    },
    req,
    {
      new: true
    }
  );
  </code></pre>
  
  <p>What I tried doing was this:</p>
  
  <pre><code>updatedDoc = await request.findOneAndUpdate(
    StaffMember,
    {
      _id: request.parameters.id
    },
    req,
    {
      new: true
    }
  );
  
  await request.aggregate(updatedDoc, [
    {
      $addFields: { activeWorkflow: { $arrayElemAt: ["$workflow", -1.0] } }
    }
  ]);
  </code></pre>
  
  <p>... but this gives me an error:</p>
  
  <blockquote>
    <p>TypeError: mongooseModelObject.aggregate is not a function</p>
  </blockquote>
  
  <p>Would I use the $addFields operator with $set, like so?</p>
  
  <pre><code>updatedDoc = await request.findOneAndUpdate(
        StaffMember,
        {
          _id: request.parameters.id
        },
        {
          $set: {
            req,
            $addFields: { activeWorkflow: { $arrayElemAt: ["$workflow", -1.0] } }
          }
        },
        {
          new: true
        }
      );
  </code></pre>
  
  <p>How does one run an aggregation as part of a function like this? A simple example would help me understand how this needs to be done -- if indeed it can be done. </p>
  
  <p>Of course, there are other ways to do this, but I'd like to take advantage of a mongo-specific way to handle this, using a mongo operation like <code>$addFields</code>. What would this look like?</p>
  
  <p>By the way, the wrapper function I'm using with aggregate looks like this:</p>
  
  <pre><code>  async aggregate(mongooseModelObject, aggregateObject = {}) {
      try {
        return await mongooseModelObject.aggregate(aggregateObject).exec();
      } catch (err) {
        this.sendError(err);
      }
    }
  </code></pre>