简体   繁体   中英

Trying to update a property in an object inside array of arrays mongodb with node js

I have an object inside an array that's inside another array... how can i update the "points" property of a certain player by his id? db structure image

tried this but it doesen't work...

 let h2h=await H2h.find({"players.$.id":req.params.id})
 let h2h = await H2h.updateMany(
   { "players.$.id": req.params.id},
   { $set: { "players.$": user} },
   {
     new: true,
   }
 );

You don't really need that first let h2h = await H2h.find(..... as you already 'find and update' the document in the updateMany method.

To update the property points for a particular player, you were really close to the solution, numberOfPointsGiven being the number you want to update it with:

let h2h = await H2h.updateMany(
   { "players.$.id": req.params.id},
   { $set: { "players.$.points": numberOfPointsGiven} }
 );

Keep in mind that updateMany will NOT return the newly edited object, as it differs from the findByIdAndX and findOneAndX . It instead returns a query indicating how many document have been updated, among other things. Please read more here

i actually wanted to update the 'name' property (the 'points' was a mistake) the correct answer is:

 let h2h=await H2h.updateMany(
//this line targets the element inside the array thats inside another array
    {"players":{$elemMatch:{$elemMatch:{id:req.params.id}}}},
//this line sets the 'name' property inside the unnamed array thats inside the players array
    { $set: { "players.$[].$[elem].name": user.nickName } },
//this line is for mongo to update only the element that matches the user's id
    {arrayFilters:[{'elem.id':req.params.id}]},

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