Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda