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

使用对象删除MongoDB文档时遇到问题,附相关代码

Troubleshooting Your MongoDB deleteOne Issue

Hey Ricky, let's walk through why your document deletion might be failing and how to fix it. Based on your code, here are the most common issues to check:

1. Verify Your Query Matches Existing Documents

MongoDB queries are case-sensitive and strict about data types. If Video_trim is a string field but trimNameToDelete is a number (or vice versa), no documents will match.

First, run this in your MongoDB shell to confirm if any documents match your query:

db.yourCollectionName.find({ Video_trim: "yourTrimNameValue" })

Replace yourCollectionName with the actual value of documentName and yourTrimNameValue with what trimNameToDelete logs out. If no results come back, your query condition is the problem.

2. Check Collection Name Spelling

Double-check that documentName is exactly the name of your collection. MongoDB collection names are also case-sensitive—if your collection is named videoTrims but documentName is set to VideoTrims, you'll be targeting the wrong collection entirely.

3. Update Your Assertion for Modern MongoDB Drivers

The result.result.n property is from older MongoDB driver versions. Newer drivers use result.deletedCount to return the number of deleted documents. Your assertion assert.equal(1, result.result.n) will fail if no documents are deleted, which might be why you're seeing errors.

Try modifying your code to log the actual deleted count instead of relying on the assertion first:

const deleteTrimByName = function (db, callback) { 
  // 获取文档集合
  const collection = db.collection(documentName);
  // 确认要删除的值
  console.log('Trying to delete trim:', trimNameToDelete);

  collection.deleteOne({ Video_trim: trimNameToDelete }, function (err, result) { 
    if (err) {
      console.error('Delete error:', err);
      return callback(err);
    }
    // 用deletedCount替代result.result.n(适配新驱动)
    console.log(`Deleted ${result.deletedCount} document(s)`);
    if (result.deletedCount === 0) {
      console.warn('No document matched the delete query!');
    }
    callback(result);
  });
};

4. Ensure trimNameToDelete Is Properly Initialized

Your console.log(trimNameToDelete) should output the exact value you expect. If it's undefined or an unexpected value, the delete query won't match anything. Make sure this variable is set before deleteTrimByName is called—async timing issues can sometimes cause variables to be uninitialized when the delete runs.

Bonus: Check File Deletion Path

You mentioned fs.unlink('./public/videos/cut...—if you're also having issues deleting the file, double-check that the file path is correct (relative paths depend on where your Node.js process is running from).

内容的提问来源于stack exchange,提问作者Ricky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:16:58