Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda