MongoDB删除函数异常:传入字符串类型property参数无法生效
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

