简体   繁体   中英

Updating a 3 levels nested array mongoose

I am trying to updated this mongdb nested array using mongoose but no luck I put all the versions that is tried may be you can connect the dots I am using findOneAndUpdate is it even possible to update items this deep?.

 // Input from Front-End taking in to account that all the ids are static for now to simplyfy thigs {Name: Jess} // Function const updateDeptArr = await Data.findOneAndUpdate( // First Version { '_id':'60cbbb23d5741b51f8fefc2b' // First user ID [`peeps._id`]: '60cbbb28d5741b51f8fefc2e', // Second ID 1st nest [`arraNames._id`]: '60cbc2d1cf7b1c3250e08dc2' // Third ID 2nd nest }, { $set: { [`peeps.$.arraNames.$.Name`]: 'Jess' }, { _id: true, new: true }) // Second Version { '_id': '60cbbb23d5741b51f8fefc2b' 'peeps': { "$elemMatch": { "_id": '60cbbb28d5741b51f8fefc2e', "arraNames._id": "60cbc2d1cf7b1c3250e08dc2" } } }, { $set: { // Test 1 [`peeps.$[outer].arraNames.$[inner].Name`]: 'Jess' //Test 2 'peeps.$[outer].arraNames.$[inner].Name': 'Jess' } }, { _id: true, new: true }) // 50% working version Not dynamic but it modify the targeted element const updateDeptArr = await Data.findOneAndUpdate( { '_id': req.body.userId, // user ID [`peeps._id`]: '60cbbb28d5741b51f8fefc2e', // Second ID }, { $set: { [`peeps.0.arraNames.0.Name`]: 'Jess' } }, { _id: true, new: true } ) // Schema { UserId, '60cbbb23d5741b51f8fefc2b' User: "", peeps [{ _id: '60cbbb28d5741b51f8fefc2e' arraNames: [{ _id:'60cbc2d1cf7b1c3250e08dc2' Name: "",// End point Name must be Jess }], }],

I want that Name to be Jess to modify the end point, there are be many names

Having nested arrays is a bad idea. I would recommend you try a more flat structure to make queries faster and simpler. having said that you can update transactions through:

 Data.findOneAndUpdate({ UserId, "60cbbb23d5741b51f8fefc2b" }, { $set: { "peeps.$.arraNames.$[j].Name": "Jess" } }, { arrayFilters: [{ "j._id": { $eq: "60cbc2d1cf7b1c3250e08dc2" } }] })

arrayFilters is passed in options for update() , updateOne(), updateMany() , findOneAndUpdate() and bulkWrite() methods. Any elements that match the condition given will be get updated.

Also see Updating a Nested Array with MongoDB and positional-filtered for how these new positional operators apply to "nested" array structures, where "arrays are within other arrays".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM