0

I am creating an API with nodejs and I have got the following dataset

[ { _id: 5ef054487c20460017dcbde8,
post_data: 'paw nisa dmme  vahi ponnaya',
likes: 2,
commentsCount: 0,
post_img: null,
isUserLiked: false,
usersLiked: [ 5eef7fc55de48230887f3aa3 ],
exp_date: 2020-06-27T00:00:00.000Z,
has_img: false,
user_id: [ [Object] ],
typology: 'post',
geometry:
 { pintype: 'Point',
   _id: 5ef054487c20460017dcbde9,
   coordinates: [Array] },
created: 1592808520819,
category: [],
createdAt: 2020-06-22T06:48:40.821Z,
updatedAt: 2020-06-22T07:29:00.148Z } ]

In there I have usersLiked array and I got the above results to posts variable and used the following code to change isUserLiked.

            posts.forEach((post) => {
                post.isUserLiked = post.usersLiked.includes(user_id)
            });

The problem is post.usersLiked.includes(user_id) is always returing false

My mongodb looks like this .

enter image description here

I have already tried post.isUserLiked = post.usersLiked.includes(mongoose.Types.ObjectId(user_id)) but it gives the same output ? What can be the problem here and how can I solve it ?

Suthura Sudharaka
  • 643
  • 10
  • 25
  • convert `Object ID` to string before comparison. – Henok Tesfaye Jun 22 '20 at 07:54
  • 1
    `id`, `user_id` and the content of `usersLiked` are objects of type [`ObjectId`](https://docs.mongodb.com/manual/reference/method/ObjectId/). `.include()` uses the [`SameValueZero`](https://tc39.es/ecma262/#sec-samevaluezero) algorithm which compares objects as objects. If they are not the same (`===`) then the result will be `false`. Convert the ids to strings and then compare them. – Andreas Jun 22 '20 at 08:01

2 Answers2

2
post.isUserLiked = post.usersLiked.some(id => id.toString() === user_id)

If user_id is not a string use .equals. Check here https://stackoverflow.com/a/11638104/8443899

Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
-1

I think the problem comes cause this dataset that you showed us, the usersLiked: [ 5eef7fc55de48230887f3aa3 ], has an array of something that's not an String.

Maybe if this ID, was an String, you can do then the usersLiked.includes('ANOTHER STRING HERE')

When i mean string, i mean should be like this: usersLiked: [ '5eef7fc55de48230887f3aa3' ]

mmonteirocl
  • 382
  • 2
  • 16
  • I dont know user_id but im meaning the array of useersLiked, what you showd us, doesn't have the quotes as an String – mmonteirocl Jun 22 '20 at 08:14