Tuesday 31 December 2019

help updating mongoose subdocument

HelloI need help updating a subdocument in mongoose and sometimes I struggle with Mongoose Documentation. I am using the most recent version v5.8.3.To give this context, I am building an app that tracks personal 1 rep max at the gym. In MongoDB I have a 'personrecords' document that look like:_id: ObjectId("5e05f6e065300b3154798773")user_id:"5e05f6e065300b3154798772"lifts: Array0: Object_id: ObjectId("5e05f7e8af6d963c6829b2c2 ")name: "Test Lift"type: "lift"preDefined: falsedate: "12/31/19"comment: "This is a test comment"personalRecord: "100 lbs"1: Object2: Objectcardio:Arrayskills:ArrayI want my user to be able to edit/update an entry.So far I have been able to access the specific entry I want to update. Below is the code (hard coding my variables for now):router.put('/:id', async (req, res) => {try {let movement = 'lifts'let id = "5e05f6e065300b3154798772"let prID = "5e05f7e8af6d963c6829b2c2"let record = await PersonalRecord.findOne({ user_id: id})console.log(record)if(movement === 'lifts'){let lift = record.lifts.id(prID)console.log(lift) // gives me the right subdocument.. but now what?   } } catch (error) {res.send(error);    }})Once I have the correct subdocument, how do I update one or all of the object key/value pairs?Lets say I want to change the 'personalRecord' and the 'comment'.​Any help would be appreciated, thanks!

Submitted December 31, 2019 at 01:29PM by la712

No comments:

Post a Comment