Oto-Obong Eshiett
Oto-Obong Eshiett

Reputation: 577

How do I find all elements that have a property value in an array of value - Mongoose

I have an a UserModel in my project which has a mobile_number property in schema structured below

const userSchema = new Schema(
    {
        firstname: {
            type: String,
            text: true,
            maxlength: 50
        },
        lastname: {
            type: String,
            text: true,
            maxlength: 50
        },
        username: {
            type: String,
            text: true,
            maxlength: 50
        },
        last_login: {
            type: Date
        },
        dob: {
            type: Date
        },
        mobile_number: [{
            type: String,
            text: true,
            maxlength: 50
        }]
    })

I also have an array of mobile numbers ['08099999394', '0809992224', '08176674394']

using this array of mobile numbers how do I get a list of the users who has a mobile number (user.mobile_number) in the array without running a for loop?

Upvotes: 0

Views: 732

Answers (1)

danial dehvan
danial dehvan

Reputation: 237

You can check if the user's number is one of the numbers in your array buy $or operator when you query the database.

Here is the official MongoDB documentation about this

or if you want to query the users that have a number ( their number is not null ) you can use this:

user.find({ mobile_number: { $ne: null } })

Upvotes: 1

Related Questions