MongoDB双数组过滤失效问题排查(ES6)
Hey there! I see you're stuck on why your outstanding array keeps coming up empty when trying to find the difference between two lists of MongoDB ObjectIDs. Let's get to the bottom of this and fix it.
The Root Cause
The issue here is that MongoDB ObjectIDs are not plain strings—they're instances of the ObjectID class. Even if two ObjectIDs have identical string representations, they're separate object references in JavaScript. The includes() method checks for strict equality (===), which fails for different objects even if their values match. That's why your filter always returns an empty array.
Solutions
1. Use the equals() Method (For ObjectID Objects)
MongoDB's ObjectID prototype has an equals() method specifically designed to compare the underlying values of two ObjectIDs. Replace your filter logic with this:
let questions = res.locals.questions; let answers = res.locals.answers; let outstanding = questions.filter(questionOid => { // Check if none of the answer ObjectIDs match the current question ObjectID return !answers.some(answerOid => answerOid.equals(questionOid)); }); console.log("The outstanding oids: ", outstanding);
2. Convert ObjectIDs to Strings First
If you prefer working with string comparisons, convert both arrays to string representations of the ObjectIDs first:
let questions = res.locals.questions; let answers = res.locals.answers; // Convert answer ObjectIDs to their string equivalents const answerStrings = answers.map(oid => oid.toString()); // Filter questions by checking if their string form isn't in answerStrings let outstanding = questions.filter(questionOid => { return !answerStrings.includes(questionOid.toString()); }); console.log("The outstanding oids: ", outstanding);
Verify the Type of Your Array Elements
First, confirm whether your questions and answers arrays contain actual ObjectID objects or just string representations. Add these logs to check:
console.log("Question element type:", typeof questions[0], questions[0] instanceof ObjectID); console.log("Answer element type:", typeof answers[0], answers[0] instanceof ObjectID);
If the logs show they're strings, your original code should work—but if they're ObjectID instances, you'll need one of the solutions above.
内容的提问来源于stack exchange,提问作者Izzi

