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

MongoDB删除函数异常:传入字符串类型property参数无法生效

Fixing the MongoDB Remove Function for Dynamic Property Names

Got it, let's sort out this issue! The problem here is how you're defining the query object in your remove call. When you write {property: value} in JavaScript, the interpreter treats property as a literal string key—not the value of the property parameter you passed into the function. So if you call removeTestObjects("myColl", "status", "inactive"), it's trying to delete documents where the field named "property" equals "inactive" (which almost certainly isn't what you want).

The Fix: Use Dynamic Property Names

There are two straightforward ways to fix this, depending on your JavaScript environment:

1. ES6+ Calculated Property Names (Cleanest Approach)

Wrap the property variable in square brackets inside the object literal. This tells JavaScript to use the value of the variable as the key name:

function removeTestObjects(collection, property, value) {
  return db.collection(collection).remove(
    { [property]: value }, // Square brackets make this dynamic
    function(err, result) {
      if (err) throw err;
      // Optional: Add feedback about the operation
      console.log(`Successfully removed ${result.deletedCount} documents`);
    }
  );
}

2. Pre-Build the Query Object (For Older Environments)

If you're working with an environment that doesn't support ES6 features, you can create an empty object first and then assign the dynamic key manually:

function removeTestObjects(collection, property, value) {
  const query = {};
  query[property] = value; // Assign the dynamic key-value pair
  return db.collection(collection).remove(query, function(err, result) {
    if (err) throw err;
  });
}

How It Works Now

When you call removeTestObjects("products", "category", "deprecated"), the query will correctly target documents where the category field equals "deprecated"—exactly what you intended.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:21:28