簡體   English   中英

React:如何在 MongoDB 中將元素添加和更新到數組中

[英]React: How to Add and update Elements into an Array in MongoDB

我正在向數據庫發送一個新項目,並且在該數據中有一個帶有一些 id 的數組。 我正在使用node 和 expressJs 所以,想法是如果存在對象,我想更新對象內部的數組。 或者該對象將在 mongodb 中創建。

問題是:第一次提交時,它會使用數組添加到數據庫中。 但是在其他點擊中,數組剛剛被新的 ID 替換。

 app.put("/destination", async (req, res) => { const email = req.query.email; const query = { email: email }; let result; if (query) { const cursor = userCarCollection.find(query); const userNewIds = req.body; result = await collection.updateOne( query, { $set: userNewIds }, { upsert: true } ); } else { result = await carCollection.insertOne(userNewCar); } res.send(result); });

我找到了解決方案的家伙。 任何不便敬請諒解。 我不得不使用$push方法而不是$set方法。 因為,我是初學者,我不能這樣想。 我的解決方案如下,並且運行良好:

 if (query) { const cursor = userCarCollection.find(query); const userNewIds = req.body.productId.toString(); result = await userCarCollection.updateOne( query, { $push: { productId: userNewIds, }, }, { upsert: true } ); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM