0

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"]
3
  • 1
    are these strings or mongoDB objectIDs? Commented Sep 9, 2020 at 7:47
  • ore show us your mongoose model in case you use mongoose Commented Sep 9, 2020 at 7:50
  • When I perform typeof() test it returns "object". They are objectIDs in mongoose, so I assume they are objectIDs? Commented Sep 9, 2020 at 7:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Oh wow, that makes sense. Except, I want to return the ones that do not find a match, so needs to have !answers.some...etc
@IsraelPeck answers.some returns either true or false, then just invert it !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.