[英]Trying to find index of ObjectId in Mongo DB with indexOf
I am trying to get the index of a specific ObjectId.我正在尝试获取特定 ObjectId 的索引。 I am getting -1, when trying to get the correct Id.
在尝试获取正确的 ID 时,我得到 -1。 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 的数组 ['60b4e7ba02edf04a840d2fb8', '60bdf9ba1752a750e4b57115']
ID "60bdf9ba1752a750e4b57115"
ID“60bdf9ba1752a750e4b57115”
INDEX -1
指数 -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"'
.您的问题是
JSON.stringify()
:正如您在 ID 的console.log
中看到的那样,变量idFetch
不是您所期望的字符串'60bdf9ba1752a750e4b57115'
,而是字符串'"60bdf9ba1752a750e4b57115"'
。 IndexOf cannot find the idFetch
and therefore returns -1
. IndexOf 找不到
idFetch
并因此返回-1
。
var idFetch = forIter[i]._id.toString();
should work.应该管用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.