0

Running the following code:

console.log(typeof req.user.models,typeof req.user.models[0],req.user.models[0] instanceof String,req.user.models[0] instanceof ObjectId,req.user.models)
console.log(typeof req.params.id,req.params.id)
console.log("includes:", req.user.models.includes(req.params.id), req.user.models.includes(ObjectId(req.params.id)))

for(let i=0;i<req.user.models.length;i++) {
  if (req.user.models[i]==req.params.id) {
    console.log("u approx")
    if(req.user.models[i]===req.params.id) {
      console.log("u exact")
    }
  }
  if (req.user.models[i]==ObjectId(req.params.id)) {
    console.log("s approx")
    if(req.user.models[i]===ObjectId(req.params.id)) {
      console.log("s exact")
    }
  }
}

prints the following:

object object false true [ 60066eac8a2f2c21f48688f2 ]
string 60066eac8a2f2c21f48688f2
includes: false false
u approx

Considering req.user.models[0] instanceof ObjectId returns true, I do not understand how req.user.models.includes(ObjectId(req.params.id)) can return false, nor how s approx and s exact cannot be printed.

Also worth noting I encountered some issue using ObjectId (or ObjectID), my solution being:

const mongo = require("mongodb");
const ObjectId = mongo.ObjectID;

Is this perhaps wrong and what is causing the issue?

1 Answer 1

2

there are three ways to solve the problem.

 1. req.user.models[i].toString()
 2. JSON.stringify(req.user.models[i])
 3. req.params.id.equals(req.user.models[i])


if (JSON.stringify(req.params.id) === JSON.stringify(req.user.models[i])) {
        console.log('This is true');
}

if (req.params.id.equals(req.user.models[i])) {
    ...
}

and you can use this code for search your string id in array of ObjectId

const exists = req.user.models.some(val => val.toString() === req.params.id) 

or

const exists = req.user.models.some(val => val.equals(req.params.id))
Sign up to request clarification or add additional context in comments.

1 Comment

Neat. I find using .some() offers the best flexibility

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.