1

I have the following user Model:

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please tell us your name!'],
    },
    email: {
        type: String,
        required: [true, 'Please provide your email'],
        //unique: true,
        lowercase: true,
        validate: [validator.isEmail, 'Please provide a valid email'],
    },
    phoneNumber: { type: String, default: '' },
    photo: {
        type: String,
        default: 'default.jpg',
    },
    // roles: [{ type: mongoose.Schema.ObjectId, ref: 'Roles' }],
    roles: [String],
    password: {
        type: String,
        required: [true, 'Please provide a password'],
        minlength: 8,
        select: false,
    },
    passwordConfirm: {
        type: String,
        required: [true, 'Please confirm your password'],
        validate: {
            // This only works on CREATE and SAVE!!!
            validator: function (el) {
                return el === this.password
            },
            message: 'Passwords are not the same!',
        },
    },
    passwordChangedAt: { type: Date, select: false },
    passwordResetToken: { type: String, select: false },
    passwordResetExpires: { type: Date, select: false },
    active: {
        type: Boolean,
        default: true,
        // select: false,
    },

    admissionDate: Date,

    positions: [
        {
            branch: {
                //branch al qeu pertenece el horario
                type: mongoose.Schema.ObjectId,
                ref: 'Branch',
            },
            area: {
                //area al que pertenece el horario
                type: mongoose.Schema.ObjectId,
                ref: 'Area',
            },
            position: {
                //area al que pertenece el horario
                type: mongoose.Schema.ObjectId,
                ref: 'Position',
            },
            salary: { type: Number, default: '' },
        },
    ],
    
    
})

where I have the attribute positions, that is an array of objects. each object has a reference for the branch, area and position that this user belongs (those are separate models).

I'm trying to create a query that can show users that belong to a certain branch and area but so far I haven't being able to create that query:

I tried with:

{
  "positions": {
    "branch": "60691ada4a9943d8eb562874", 
    "area": "60691aea4a9943d8eb562875"
   }
}

tried using the $in operator, the $all operator, the $elemMatch operator and so far nothing has worked.

Can you please help me build the correct query to get the elements needed.

Thank you very much in advance.

EDIT: testing the filter with $elemMatch: enter image description here

it should find this element: enter image description here

1 Answer 1

1

You can use $elemMatch, to match both fields in same elements

db.collection.find({
  positions: {
    $elemMatch: {
      branch: "60691ada4a9943d8eb562874",
      area: "60691aea4a9943d8eb562875"
    }
  }
})

Playground

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

3 Comments

hi turivishal, I tried that solution on Compass but it doesn't find any result. I updated the question with the result test with Compass.
Found it, thanks to your solution just had to dig a little deeper, I had to add the ObjectId('id') for the Ids. { positions: { $elemMatch: { branch: ObjectId('6069fd648693cbe8ec5a6cff'), area: ObjectId('60691aea4a9943d8eb562875') } } }
yes for the compass you have to convert it to ObjectId, i have provided solution for mongoose as per your schema, you don't need to convert it because you have specified type as object id in schema.

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.