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

140
Visualizações
How to add new value with same key to document

I need to write down a category and its cost in category object. Now, in my code example, I am adding the products: $50 category to the user. After execution, 'categories': { products: '50$' } is displayed in the console. But if you add products: 1000$ again, it will overwrite and output 'categories': { products: '1000$' }. And I need to display 'categories': { products: '$50' , products: '$1000' }. How can this be implemented?

mongoClient.connect(function (err, client) {
  if (err) return console.log(err);

  const db = client.db("db");
  const col = db.collection("coll");
  col.findOneAndUpdate(
    {
      name: "User1",
    },
    {
      $set: {
        "сategories.products": "50$",
      },
    },
    function (err, result) {
      console.log(result);
      client.close();
    }
  );
});

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Instead of

$set: {
  "сategories.products": "50$"
}

use

$addToSet: {
  сategories: {
    products: "1000$"
  }
}
about 4 years ago · Santiago Trujillo Relatório

0

You should change the key name like products_2

about 4 years ago · Santiago Trujillo Relatório

0

Well if I understood you correctly you have an object like categories:{products:$50} but you want that whenever you post a new price it should get added to the object not overwrite it.

I think that is not possible either every time you create a new object like {products1:$50, products2:$1000} and set your categories field to be equal to this new object

OR

you should make your model like categories:{products:[]}. So, that you can just push the new price in the array.

about 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