Home > Mobile >  How to check if item has already existed in array in MongoBD?
How to check if item has already existed in array in MongoBD?

Time:01-08

How do I check if item has already existed in array? I have a schema model like below and I want to check if user id existed in any fields (cute, sweet, sexy...).

  const UserSchema = new Schema({
      ...
      vote_user: {
        cute: [Schema.Types.ObjectId], 
        sweet: [Schema.Types.ObjectId], 
        sexy: [Schema.Types.ObjectId],
      },
      ...

  })

CodePudding user response:

One option is using $or:

db.collection.find(
  {$or: [
    {cute: userId)},
    {sweet: userId)},
    {sexy: userId)}
  ]}
)

See how it works on the playground example

  • Related