Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Mongoose add to array of nested array if exists create otherwise

i'm trying to accomplish the following in mongoose:

Say i have the following collection

{
    "_id": {
        "$oid": "111"
    },
    "email": "xxx@mail.com",
    "givenName": "xxx",
    "familyName": "xxx",
    "favoriteProducts": [{
        "soldTo": "33040404",
        "skus": ["W0541", "W2402"]
    }, {
        "soldTo": "1223",
        "skus": ["12334"]
    }]
}

i want to be able to add a sku to the favorite products array based on soldTo and _id. When doing this there are two possible scenarios.

a. There is already an object in favoriteProducts with the given soldTo in which case the sku is simply added to the array.(for example add sku '12300' to soldTo '1223' for id '111')

b. There is no object with the given soldTo yet in which case this object need to be created with the given sku and soldTo. (for example add sku '123' to soldTo '321' for id '111')

so far i've done this but i feel like there is a way to do it in one query instead.

 private async test() {
    const soldTo = '1223';
    const sku = '12300';
    const id = '111';
    const hasFavoriteForSoldTo = await userModel.exists({
      _id: id,
      'favoriteProducts.soldTo': soldTo,
    });

    if (!hasFavoriteForSoldTo) {
      await userModel
        .updateOne(
          {
            _id: id,
          },
          { $addToSet: { favoriteProducts: { skus: [sku], soldTo } } },
        )
        .exec();
    } else {
      await userModel
        .updateOne(
          {
            _id: id,
            'favoriteProducts.soldTo': soldTo,
          },
          { $addToSet: { 'favoriteProducts.$.skus': sku } }
        )
        .exec();
    }
  }

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use update-documents-with-aggregation-pipeline

Check out mongo play ground below. Not sure you want Output 1 or Output 2.

Output 1

db.collection.update({
  _id: { "$oid": "111222333444555666777888" }
},
[
  {
    $set: {
      favoriteProducts: {
        $cond: {
          if: { $in: [ "1223", "$favoriteProducts.soldTo" ] },
          then: {
            $map: {
              input: "$favoriteProducts",
              as: "f",
              in: {
                $cond: {
                  if: { $eq: [ "1223", "$$f.soldTo" ] },
                  then: { $mergeObjects: [ "$$f", { skus: [ "12300" ] } ] },
                  else: "$$f"
                }
              }
            }
          },
          else: {
            $concatArrays: [ "$favoriteProducts", [ { skus: [ "12300" ], soldTo: "1223" } ] ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

mongoplayground


Output 2

db.collection.update({
  _id: { "$oid": "111222333444555666777888" }
},
[
  {
    $set: {
      favoriteProducts: {
        $cond: {
          if: { $in: [ "1223", "$favoriteProducts.soldTo" ] },
          then: {
            $map: {
              input: "$favoriteProducts",
              as: "f",
              in: {
                $cond: {
                  if: { $eq: [ "1223", "$$f.soldTo" ] },
                  then: {
                    $mergeObjects: [
                      "$$f",
                      { skus: { $concatArrays: [ [ "12300" ], "$$f.skus" ] } }
                    ]
                  },
                  else: "$$f"
                }
              }
            }
          },
          else: {
            $concatArrays: [ "$favoriteProducts", [ { skus: [ "12300" ], soldTo: "1223" } ] ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

mongoplayground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!