Having trouble updating a field with mixed types in my mongoose schema. Although I acknowledge this may not be the ideal schema setup, there are specific reasons why it's structured this way. My goal is to perform array-like operations using JavaScript, such as pushing elements. Additionally, I am looking to access the index of the current document being iterated within nested arrays, specifically in the 'tags' field. Here is an example:
Mongoose Schema
let user = {
name : String,
email : String,
tags : []
}
The 'tags' field is dynamically generated upon creating a user and can result in a structure like this after inserting the user into the database:
tags : [
[{obj1}, {obj2}, {obj3}, ...],
[...],
[...],
[...],
[...]
]
My objective is to add a new document to the nested array using traditional JavaScript methods.
user.tags[0].forEach(obj, index){
// Perform operations here with obj and index
// Unsure how to update a nested array using the MongoDB $push operator, resorting to 'js array push' method
let newObj = { foo: bar }
user.tags[0].push(newObj)
user.save()
}
Following testing on Postman, the operation seems successful, returning the inserted item. However, I've noticed two issues:
- The changes are not persistent in the database, while the response in Postman shows otherwise:
{
name : bar,
email : foo,
tags : [
[{ foo : bar}], // from the last push operation performed
[],
[],
[]...
...
]
}
- Subsequent 'push' operations to any array index (e.g., 0th index) replace the current object instead of appending it:
user.tags[0].push(obj)
===> this replaces the first object in the postman response, although it does not reflect in the database because the changes are not persistent
Any assistance in achieving this would be highly appreciated. I am still learning about these concepts, so alternative solutions to tackle the same problem are also welcome. Thank you! :)