Epple
Epple

Reputation: 982

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

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],
      },
      ...

  })

Upvotes: 1

Views: 21

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

One option is using $or:

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

See how it works on the playground example

Upvotes: 1

Related Questions