Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.includes always false javascript

I have the following object

{ _id: 58ae39c54473f9cfd4eb29b6,
  email: '[email protected]',
  name: 'Another Club Renamed',
  __v: 0,
  createdEvents: [],
  instructors: [ 58a5ac4f84230a2117d1d6cb, 111111111111111111111111 ],
  members: [] }

when I use the method

object.instructors.includes(58a5ac4f84230a2117d1d6cb) object.instructors.includes(111111111111111111111111)

or

object.instructors.includes('58a5ac4f84230a2117d1d6cb') object.instructors.includes("111111111111111111111111")

the result is always false am I doing something incorrect?

Array.isArray(club.instructors) returns true

EDIT: The object is a mongoose.document. The object above is exactly how it gets logged to the console when I execute

Club.findById(id (err, club) =>{
    console.log(club);
})
like image 395
xerotolerant Avatar asked Dec 10 '22 12:12

xerotolerant


1 Answers

the mongo _id is 12-byte BSON type ObjectId,

So normal object.instructors.includes('58a5ac4f84230a2117d1d6cb') means you are comparing a raw string to an ObjectId,which is not a valid integer or string, which will always return FALSE.

NOTE: Tips for further understanding


use lodash to check the same ObjectId stored in multiple collections

npm i lodash --save

in your file.js

const _ = require('lodash');

lodash _.isEqual performs a deep comparison between two values to determine if they are equivalent

use lodash and perform _.isEqual for deep comparing

_.isEqual(object._id, '58ae39c54473f9cfd4eb29b6') // false
_.isEqual(object.instructor[0], '58a5ac4f84230a2117d1d6cb') // false

suppose the id 58ae39c54473f9cfd4eb29b6 comes from two different mongodb documents

collection USERS: [{_id: 58ae39c54473f9cfd4eb29b6, name: 'user1' }] suppose this user is referenced to rooms collection:

collection ROOMS: [{_id: ObjectId, name: 'room1', userId: 58ae39c54473f9cfd4eb29b6}]

if you do a normal comparison=== or includes like this

if (user[0]._id === rooms[0].userId) // false due to different instances

_.isEqual(user[0]._id, rooms[0].userId) // true performs deep comparison
like image 151
Parwat Kunwar Avatar answered Dec 26 '22 17:12

Parwat Kunwar