简体   繁体   中英

Trying to find index of ObjectId in Mongo DB with indexOf

I am trying to get the index of a specific ObjectId. I am getting -1, when trying to get the correct Id. What am I doing wrong?

console.log("Array of Id's ", userResult[0].reservations)
var idFetch = JSON.stringify(forIter[i]._id)
console.log("ID ", idFetch)
var indexOfUserReservationCondition = userResult[0].reservations.indexOf(idFetch)
console.log("INDEX ", indexOfUserReservationCondition)

Array of Id's [ '60b4e7ba02edf04a840d2fb8', '60bdf9ba1752a750e4b57115' ]

ID "60bdf9ba1752a750e4b57115"

INDEX -1

 let userResult = [{ "reservations": ['60b4e7ba02edf04a840d2fb8', '60bdf9ba1752a750e4b57115'] }] console.log("Array of Id's ", userResult[0].reservations) var idFetch = '60b4e7ba02edf04a840d2fb8' var indexOfUserReservationCondition = userResult[0].reservations.indexOf(idFetch) console.log("INDEX ", indexOfUserReservationCondition)

Your problem is the JSON.stringify() : As you can see in the console.log of the ID, the variable idFetch is not, as you expect, the string '60bdf9ba1752a750e4b57115' , but instead the string '"60bdf9ba1752a750e4b57115"' . IndexOf cannot find the idFetch and therefore returns -1 .

var idFetch = forIter[i]._id.toString();

should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM