Izzi
Izzi

Reputation: 2622

Filtering two MongoDB arrays not working (ES6)

I am asking MongoDB for two arrays of objectIDs, and then trying to compare the two arrays to find the difference.

I'm also passing the arrays through express middleware using res.locals.

Here is the code:

let questions = res.locals.questions;
let answers = res.locals.answers;
let outstanding = questions.filter(oid => !answers.includes(oid));

console.log("The outstanding oids: "+outstanding)

The result is always blank.

Maybe something to do with MongoDB's format, or the res.locals format? Appreciate any suggestions.

Here is what the two arrays look like:

questions: ["5f522bc55dd8993e58283526","5f522ab45dd8993e58283521","5f522ba65dd8993e58283525","5f522a5e5dd8993e5828351f","5f47a9a0b1764c3e285d4666"]

answers: ["5f522ab45dd8993e58283521","5f522bc55dd8993e58283526"]

Upvotes: 0

Views: 45

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14904

I guess your values inside of the array are ObjectIDs and not strings so you cannot just compare them with like == operator.

Thankfully mongoose provides .equals() to compare object IDs.

let outstanding = questions.filter(oid => !answers.some(answer => oid.equals(answer)));

http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#equals

Upvotes: 1

Related Questions