Search code examples
node.jsmongodbmongoose

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

  })

Solution

  • One option is using $or:

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

    See how it works on the playground example