I am having a problem when performing a push to a nested array, I am trying to add one or more objects within the nested array "fieldList", when I execute the push it tells me ok but when I check it it has not updated it.
{
_id: ObjectId('6628363d6ed5718acbd2af72'),
label: 'Movimiento Vehicular IDAAN',
folders: [
{
name: 'Datos Generales',
fieldList: [],
_id: ObjectId('6628367b6ed5718acbd2af9f')
},
{
name: 'Datos de Vehículo y Conductor',
fieldList: [],
_id: ObjectId('6628555de630217d0abafcc5')
}
],
createdAt: ISODate('2024-04-23T22:29:17.213Z'),
updatedAt: ISODate('2024-04-24T00:42:05.879Z')
}
I am trying to add it with $push
and the dot notation { $push: { "folders.fieldList": newfield}}
tells me that it was executed ok but it is not added. This is the code I am using:
Object to add:
{
"name": "Dia",
"label": "Dia",
"order": 11,
"type": "number",
"requ": true,
"par": "Datos Generales"
}
Update Script:
export const newfieldwithfolder = async (req: Request, res: Response) => {
try {
const { name, label, order, type, requ, par } = req.body;
const query = { _id: req.params.id };
const updateQuery = new Fields({
name,
label,
order,
type,
requ,
par,
});
const newfield = { $push: { "folders.fieldList": updateQuery } };
const result = await Template.updateOne(query, newfield);
console.log(result);
res.status(201).json({ message: "Fields have been added successfully!" });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: "Something went Wrong!" });
}
};
2
Answers
@prasad_ has already answered it. The objective of this post is to add some context to the the same answer.
Short answer:
Array of sub documents, and Nested array of sub documents as this original question belongs to, are updated using filtered positional operator $[]. The respective arrays are to be queried first and its indexes are found and used in updating. The filtered positional operation in conjunction with arrayFilters is doing this job. The section “Action log” enclosed below would have sample statements in this regard. Request read the section in order with the help of comments enclosed over there.
Detailed answer:
It is a case of accessing or updating a nested document structure.
As we know, nested structures can be mainly of two types:
For brevity and consistency while reading, “Sub documents” and “Array of sub documents” are the two terms used in the following sections.
Sub documents are relatively simple to handle as it is basically a grouping mechanism. The notable point is that all keys in a Sub document are still identifiable by the _id of a top level document and accessible by dot notation.
A sample document with one sub document
The Sub document { a : 1} above is identifiable by the top level document _id and its key “a” is accessible by dot notation as below :
However, an Array of sub documents is more than a simple Sub document.
Although like a Sub document, an Array of sub documents is still identifiable by the top level _id, and accessible by dot notation, still the very “array nature” differentiates it from the simplicity of a Sub document. Its “array nature” necessitates another dimension – “position” or “index”, also to be taken care. The fundamental point is that the respective arrays need to be searched and the array indexes are to be found prior to access. This is what it makes different from accessing a simple Sub document. The same steps are involved in the case of a Nested Array of sub documents as well. Under this background, the following action log may make more sense.
Action log:
filtered positional operator $[]
If you specify the field name from the object in the
folders
array that you want to update you can use the$
positional operator to only update that element from thefolders
array and push your new object into thatfieldList
array.Looking at your object that you want to push, you have a
"par": "Datos Generales"
key value so assuming this refers thefolders.name
field you can do:See HERE for a simple example using the
db.collection.update()
method.