$in requires an array as a second argument, found: missing

First option –> Use aggregation

Because your some of the documents in your collection may or may not contain permissions field or is type not equal to array that’s why you are getting this error.

You can find the $type of the field and if it is not an array or not exists in your document than you can add it as an array with $addFields and $cond aggregation

db.collection.aggregate([
  { "$addFields": {
    "permissions": {
      "$cond": {
        "if": {
          "$ne": [ { "$type": "$permissions" }, "array" ]
        },
        "then": [],
        "else": "$permissions"
      }
    }
  }},
  { "$project": {
    "filteredChildren": {
      "$filter": {
        "input": "$moduleChildren",
        "as": "moduleChild",
        "cond": {
          "$in": [ "$$moduleChild._id", "$permissions" ]
        }
      }
    }
  }}
])

Second option –>

Go to your mongo shell or robomongo on any GUI you are using and run
this command

db.collection.update(
  { "permissions": { "$ne": { "$type": "array" } } },
  { "$set": { "permissions": [] } },
  { "multi": true }
)

Leave a Comment