Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();
    }
  );
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of

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

use

$addToSet: {
  сategories: {
    products: "1000$"
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading