Home > Back-end >  Mongoose check specific element array length
Mongoose check specific element array length

Time:06-10

how to find array length from a specific mongoose model ?

{
  "_id": {
    "$oid": "626cf1ccb6da65761db4b146"
  },
  "ID_NUM": "ID=2796414693",
  "SET_ARRAY": [
    "sruMkdGUeRbWZz6FSz",
    "6U7ugxem7Y0/ellBUF"
  ],
  "__v": 0
}
  1. I did const lens = await model.findOne({ ID_NUM: "ID=2796414693" })
  2. then console.log(lens.SET_ARRAY.length)
  3. I get no error and no result.

CodePudding user response:

You can use $size of mongo aggregate:

const lens = await model.findOne(
  [{
      $match: {
        ID_NUM: "ID=2796414693",
      }
    },
    {
      $project: {
        _id: 0,
        ARRAY_LEN: {
          $size: "$SET_ARRAY"
        }
      }
    }
  ]
)

  • Related