3

How do I check if an element of an array belongs to another array in Mongoose? For example, I have a document:

const userSchema = new mongoose.Schema({
name: String,
favor:Array
})

user1 = {
name:'John',
favor : ['banana', 'apple', 'eggs'].
}

user 2= {
name:'Ethan',
favor : ['apple', 'eggs'].
}

and I have an Array

const array = ['eggs', 'banana']

I want to get user1. How can I do with mongoose?

1 Answer 1

5

You should use $all operator for this scenario

db.collection.find({
  favor: {
    $all: [
      "eggs",
      "banana"
    ]
  }
}) 

https://docs.mongodb.com/manual/reference/operator/query/all/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.