0

Here is my code in Node:

The results will always be "No" even if the objects are the same object. i tried with "==" and same answer - "no"

  const recipe = await getRecipes(req.params.id); \\ID
  let user = await User.findById(req.user._id); \\ user
  user.recipes.forEach((item) => {

    console.log(item._id); \\ 5f196683308447452cd2c018
    console.log(recipe._id); \\ 5f196683308447452cd2c018
    
    if (item._id === recipe._id) {
      console.log("yes");
    } else {
      console.log("no");
    }
  });
});  ```
4
  • You would get a lot of "no" and at most one "yes". Are you sure you're not overlooking it? Commented Jul 28, 2020 at 10:24
  • i really dont understand you. Commented Jul 28, 2020 at 10:27
  • You are looping through many recipes. At most one of them will have the same ID as recipe._id - that one would print "yes" in the console. Everything else would print "no". Are you sure you're not just missing the "yes"? Commented Jul 28, 2020 at 10:29
  • i had only 1 recipe in that array. Commented Jul 28, 2020 at 10:49

1 Answer 1

1

It keeps outputting 'no' because you are comparing 2 different Mongo ObjectId objects.

For example, console.log({a:1} === {a:1}) is false since they are 2 different objects.

If you really wanted to check by the ObjectId, you could do:

item._id.toString() === recipe._id.toString()

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

5 Comments

Glad to have helped! :)
other than using forEach you should consider using findIndex method.
can you give me example for that?
findIndex() or find() just optimizes the search a bit since it simply returns the first element that it finds instead of going through each element in the array by using forEach()
how do i use the findIndex instead of foreach?

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.