0
this._MyModel.findOneAndUpdate(
    { email },
    {
      $set: {
        'tradeAccount': {
          limitType,
          limit,
        }
      },
      $push: {
        'tradeAccount.history': history
      }
    }
  );

I want to add another object into an existing array using $push but in the same time I am performing another update on the same object using $set.

I know that I cannot use two operators on the same field such as ($set and $push).

I wonder if there is another way to add another object into an existing array using $set, or if there is any other way to do this in the same update request.

I was thinking of updating the array using $set by retrieving the existing history and concatenate with the new one. But that requires an extra call to the db.

1 Answer 1

1

You can use

this._MyModel.findOneAndUpdate(
  { email },
  {
    $set: {
      'tradeAccount'.'limitType': limitType,
      'tradeAccount'.'limit': limit
    },
    $push: {
      'tradeAccount.history': history
    }
  }
);

This should update the limitType and limit fields, and then push onto history. You aren't performing multiple queries on the same field this way because you aren't doing anything directly to 'tradeAccount'.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems like something that worths trying. I already separated the history update from user update, because I think this approach follows closely the SOLID principle. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.