简体   繁体   English

如何使用 Mongoose 更新 MongoDB 集合内的数组内的 Object

[英]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例如,我想将 First Expense Name 从 Bike 更新为 Bike Rental & Amount 从 250 到 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.整个集合的 ObjectID 为 607bbb07e1ebb63a3033af15 将从前端发送到后端。

I am using Express, Mongoose.我正在使用 Express,Mongoose。

You can run update on the model you have created like this:您可以在您创建的 model 上运行更新,如下所示:

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.同样,您可以对 object 中的任何键执行此操作,前提是该键存在于其中。 Now this will check the现在这将检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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