Bill
Bill

Reputation: 5150

Mongoose Aggregate: ObjectId from variable $in array not returning true

myId is a an id with the value of 5dfe303c5eb482ec2672217d and $amIinThisArray.userId is also 5dfe303c5eb482ec2672217d so I expect imFollowing to be true but its always false.

const myId = '5dfe303c5eb482ec2672217d';
const followers = await userModel.aggregate([
         { $addFields: {
            avatarId: '$followerData.shared.avatarId',
            fullName: '$followerData.shared.fullName',
            imFollowing: {
              $in: [ // <==== DoesMongoose support $in ??
                  myId, // <==== Does this variable need to be converted to some type??
                  '$amIinThisArray.userId',
              ],
          },
        },

When I test this in a MongoDB IDE with...

            "$addFields": {
                "avatarId": "$followerData.shared.avatarId",
                "fullName": "$followerData.shared.fullName"
                "imFollowing": {
                    "$in": [
                        new ObjectID("5dfe303c5eb482ec2672217d"),
                        "$amIinThisArray.userId"
                    ]
                },    
            }

It returns true!

Why?

Does myId need to be converted to some special type?

Upvotes: 1

Views: 84

Answers (1)

Guru Prasad mohapatra
Guru Prasad mohapatra

Reputation: 1969

You can convert the String id to ObjectId by

let mongoose = require('mongoose');
   const objectId=mongoose.Types.ObjectId("5dfe303c5eb482ec2672217d");

Now you can use the objectId

Upvotes: 1

Related Questions