I've been working on the code below to create a new subdocument within an existing subdocument. The structure is as follows:
User -> (Many Comments) -> (Many Ratings).
The rating object is a simple JavaScript object with the format;
rating: {
userId: "userId",
rating: 4
}
For the comment at index [0], I'm trying to add a new rating using the following code;
db.getCollection('Users').update(
{id: "user123", },
{
$push: {
comments[0].ratings: rating
}
})
When I ran this in the mongo console, with a test string for the rating value, I received the error message;
Error: Line 5: Unexpected token [
To overcome this, I tried enclosing commas around comments[0];
db.getCollection('Insights').update(
{id: "b5e5bf69-071b-4af2-99b2-5165b47499cb", },
{
$push: {
"comments[0].ratings": "test"
}
})
This update was successful;
Updated 1 existing record(s) in 2ms
However, the subdocument does not appear as expected.
If someone could guide me in the right direction, I would greatly appreciate it.