0

I have a collection with Products. The collection is structured like this:

{
        "_id": "150",
        "name": "Milk",
        "description": "Skimmed",
        "price": "10",
},

I want to add a new Object in that array called 'ratings' which would simply take in 'email' and 'ratings'

This would look like:

   {
        "_id": "150",
        "name": "Milk",
        "description": "Skimmed",
        "price": "10",
        "ratings": [
                  { 
                    "email": "xyz@mail.com",
                    "rating": "5"
                  }
                  ]
}

However, I want 'Milk' to have more ratings than just one. Such that I can loop through the ratings at the front-end and output an average. Essentially, anytime a user rates 'milk' i want it to get added to the same Array? I'm new to this and hence can't explain in specific terms. Basically:

{
            "_id": "150",
            "name": "Milk",
            "description": "Skimmed",
            "price": "10",
            "ratings": [
                      { 
                        "email": "xyz@mail.com",
                        "rating": "5"
                      },
                      { 
                       "email": "abc@mail.com",
                       "rating": "3"
                      },
                      { 
                       "email": "def@mail.com",
                       "rating": "1"
                      },
                      ]
}

Using Express, I created a router.post that looks like this.

router.post('/', async (req, res) => { 
    const rate = await loadProducts();
try {
    rate.insertOne(

    {
    "ratings": 
    [{
        "email":req.body.email,
        "rating":req.body.rating
    }]
}); 
} catch (error) {
    console.log(error);
}

This is obviously not the way to do it as posting via it creates a new Array in the collection. I want it to basically Find the product using "_id", something I will provide using the front-end, and add 'ratings' to that "_id"

Extremely sorry for my novice explanation. Trying to get a grip of this.

Any help will be highly appreciated.

Calv
  • 125
  • 2
  • 11
  • If you are seeking for combing two collections into one, take a look at this: https://stackoverflow.com/questions/5681851/mongodb-combine-data-from-multiple-collections-into-one-how – Limboer Jan 21 '20 at 17:20

1 Answers1

0

You can check this update operators for mongoDB

$push
$addToSet

https://docs.mongodb.com/manual/reference/operator/update-array/

Ahmed Kesha
  • 810
  • 5
  • 11