You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 trial document as the filter for updateOne() 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 in matchedCount: 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 subsequent findOne() might execute before the insert finishes, leading to unexpected null results.
  • Undeclared variables: Variables like foundPoint, pointArray, and loop variables lack let/const declarations, causing global scope leaks and potential bugs.
  • Typos: Undefined variables like value (should be val) and misspelled newId (should be newID) 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/const to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:50:20