MongoError:$in needs an array 问题求助(附fileIds输出示例)
MongoError: $in needs an array Issue Hey there, let's break down why you're hitting this error and how to fix it quickly!
The Root Problem
Looking at your console.log(fileIds) output:
{ '0': 5a8f24ab281bd22cd940530b, '1': 5a8f24ab281bd22cd940530c }
This is a plain JavaScript object, not an array. MongoDB's $in operator strictly requires an array of values to match against—so passing an object here triggers the error you're seeing.
The Solution: Convert the Object to an Array
You just need to extract the values from your fileIds object and turn them into a proper array. The easiest way to do this is using Object.values():
// Convert the object to an array of its values const fileIdsArray = Object.values(fileIds); // Now use this array in your $in query db.collection('your-collection-name').find({ yourFieldName: { $in: fileIdsArray } });
After this conversion, fileIdsArray will look like this (exactly what MongoDB expects):
[5a8f24ab281bd22cd940530b, 5a8f24ab281bd22cd940530c]
Alternative Conversion Methods (If Needed)
If for some reason Object.values() isn't an option (e.g., older environment support), you can use these alternatives:
- Array.from() (works for array-like objects):
const fileIdsArray = Array.from(fileIds); - Spread operator (also for array-like objects with a
lengthproperty):const fileIdsArray = [...fileIds];
Just make sure to verify the converted array with console.log(fileIdsArray) before passing it to your query—once it's a proper array, the $in error should disappear!
内容的提问来源于stack exchange,提问作者ankitbaid11326

