MongoDB updateOne()无报错但未生效,返回匹配数为0,求解决
Fix for MongoDB updateOne() Not Modifying Points Field
Your update fails due to several critical issues in the code. Here's the breakdown of problems and how to resolve them:
Key Issues & Fixes
- Incorrect update filter: Using the full
trialdocument as the filter forupdateOne()means MongoDB looks for an exact match of the document as it was fetched. Any local changes to the document will break this match, resulting inmatchedCount: 0. Replace this with the document's_id—a unique, unchanging identifier—to reliably target the correct entry. - Missing await on insertOne: The
insertOne()call isn't awaited, so the subsequentfindOne()might execute before the insert finishes, leading to unexpectednullresults. - Undeclared variables: Variables like
foundPoint,pointArray, and loop variables lacklet/constdeclarations, causing global scope leaks and potential bugs. - Typos: Undefined variables like
value(should beval) and misspellednewId(should benewID) break the update logic. - Inefficient loop updates: Updating the collection inside the loop is unnecessary—modify the array first, then perform a single update at the end.
Corrected Code
async function checkPoint(arrayPoint, collection, origin) { let trial = await collection.findOne({ 'Points': { $exists: true } }); if (trial === null) { await collection.insertOne({ Points: ['floater', '1'] }); trial = await collection.findOne({ 'Points': { $exists: true } }); } let foundPoint = false; const pointArray = [...trial.Points]; // Create a copy to avoid mutating the original document for (let i = 0; i < pointArray.length; i++) { const newPoint = pointArray[i]; const newID = newPoint[0]; let newValue = newPoint[1]; if (newID === arrayPoint) { console.log(`It seems we have data! Aha! ${arrayPoint}`); let val = parseInt(newValue); val += 1; newValue = val.toString(); pointArray[i] = [newID, newValue]; foundPoint = true; } else { console.log(`It seems id: ${arrayPoint} doesn't match id ${newID}`); } } if (!foundPoint) { pointArray.push([arrayPoint, '1']); } // Use _id to target the exact document await collection.updateOne( { _id: trial._id }, { $set: { 'Points': pointArray } } ); }
Explanation
- Filter by _id: Ensures we always target the correct document, even if local data changes.
- Await insertOne: Guarantees the insert operation completes before fetching the document again.
- Proper variable scoping: All variables are declared with
let/constto avoid global scope pollution. - Array copy: Prevents unintended mutation of the original document object retrieved from MongoDB.
- Single update: Modifies the array locally first, then updates the collection once for better performance.
内容的提问来源于stack exchange,提问作者Dougal McSmith
相关产品推荐
相关产品推荐

