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

95
Visualizações
pushing a new card object to the nested array of objects

I have this structure in my Accounts Model:

{
  cards: {
    starter: [],
    intermediate: [],
    advanced: [ {Object}, {Object}, {Object} ]
  },
  firstName: 'Sepideh',
  email: 'sepideh@example.com',
}

The Objects inside cards.advanced array above are like:

{
  cards: [
    { // this is a single card object 
      cardTitle: 'this card is for you',
      performance: [],
      cardID: 32,
    }
  ],
  unit: 3 // this is the unit we want to push our new card object into
}

Assuming I can access the document above (or account in other words) with the given email:

const account = await db.Account.findOne({ email: 'sepideh@example.com' });

How can we push a new card object into the nested cards array with unit: 3 (yes so far this is the only unit) property and save Sepideh account like this:

{
    cards: {
        starter: [],
        intermediate: [],
        advanced: [
            {
                cards: [
                    { // this is a single card object 
                        cardTitle: 'this card is for you',
                        performance: [],
                        cardID: 32,
                    }

                    { // this is new pushed card object 
                        cardTitle: 'this card is for me',
                        performance: [],
                        cardID: 33,
                    }
                ],
                unit: 3 // this is the unit we want to push our new card object into
            },
            {Object},
            {Object}
        ] // end of advanced array
    },
    firstName: 'Sepideh',
    email: 'sepideh@example.com',
}

I have tried to select the unit 3 of the document using these guys and none of them worked:

const userUnit = await account.findOne({'cards.advanced.unit': unit});

const userUnit = await account.findOne({'cards.advanced.unit': unit});

const userUnit = await account.find({}, {'cards.advanced.unit': {$elemMatch: {unit: unit}}}); 

const userUnit = await db.Account.findOne({ email: email, 'cards.advanced.unit': unit});

Then I would push my new card object to the userUnit and call await account.save();

The only thing which is working is pure JavaScript code like this to select:

const userUnit = account.cards.advanced.find(e => e.unit == unit);

This time I cannot save the changes to the database... (I don't know how to save it..)

How would you do this?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use the $push operator directly along with the $ positional operator which allows you to specify which sub-element should be updated:

await db.Account.update({ email: "sepideh@example.com", "cards.advanced.unit": 3 },
        { $push: { "cards.advanced.$.cards": { cardTitle: 'this card is for me', performance: [], cardID: 33 } } })

If you want your path to be evaluated dynamically you can use computed property names:

let path = "advanced";
await db.Account.update(
    { email: "sepideh@example.com", ["cards." + path + ".unit"]: 3 },            
    { $push: { ["cards." + path + ".$.cards"]: { cardTitle: 'this card is for me', performance: [], cardID: 33 } } })

Mongo Playground

over 4 years ago · Santiago Trujillo 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