Home > Enterprise >  Mongoose add condition in Select
Mongoose add condition in Select

Time:04-20

I want to get specific fields in mongoose based on a condition. This is the case scenario I want This is the data:

{
    ...
    businessInfo: {
        isBusinessVerified: true
        categories: [...]
    }
    ...
}

and I want when isBusinessVerified is true to return the whole businessInfo object and if not return only businessInfo with isBusinessVerified field

Here is my implementation for now:

    const condition = {
      ...
      businessInfo: {
        $cond: [
          {
            $eq: ['$businessInfo.isBusinessVerified', true],
          },
          '$businessInfo',
          '$$REMOVE',
        ],
      },
    };
    const userData = await userProvider.findOne({ _id: userId }, condition);

Also, This is working but I'm not getting businessInfo with isBusinessVerified inside it only. And I'm getting this error However its working server error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

CodePudding user response:

You are actually on the right track to use $cond to wrangle your businessInfo object. Just put the simple case(i.e. only the flag is returned) in else should be fine.

db.collection.aggregate([
  {
    "$addFields": {
      "businessInfo": {
        "$cond": {
          "if": "$businessInfo.isBusinessVerified",
          "then": "$businessInfo",
          "else": {
            businessInfo: {
              isBusinessVerified: "$businessInfo.isBusinessVerified"
            }
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

  • Related