简体   繁体   中英

How to Update an Object inside an Array inside a MongoDB Collection using Mongoose

This Is An Expense Tracker Application

I'm Trying to Make An Update Route where The User Can Update the Value of An Expense

这是我的数据库模型的快照

For Example, I want to update the First Expense Name from Bike to Bike Rental & Amount from 250 to 500

And similarly, make a generic endpoint where the user can update any expense whenever necessary

Here A Snapshot of My Express Get Route & The Patch route which I want to fill

在此处输入图像描述

The ObjectID of the Entire Collection which is 607bbb07e1ebb63a3033af15 will be sent to the backend from the Frontend.

I am using Express, Mongoose.

You can run update on the model you have created like this:

const filter = {_id :"(*User Id Here*)", "Expenses._id": "(*Expense Id Here*)"}; //check the type of _id if this doesn't work
const query = {$set: {"Expenses.$.Name" : "value"}};

User.update(filter, query);

Or,

User.update({_id :"ObjectId(pass id)", "Expense._id" : ObjectId'pass id'}, {'$set': {'Expenses.$.Name': 'name update'});

Similarly, You can do this for any key in the object provided that the key exists in it. Now this will check the

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