0

I have a Schema Classroom with properties:
  _id
  studentEmails (array of Strings. Each student has an unique email)

I am given an array of Classroom ids, and I want to find every student email that belongs one of those classrooms, without duplicates. How do I do this? I was thinking I could get every student email and then remove duplicates later, but I would much rather do it through mongoose.

For example, if I had the following classrooms:

_id: 1
studentEmails: ["[email protected]", "[email protected]"]

_id: 2
studentEmails: ["[email protected]", "[email protected]"]

And the following query parameter:

[1, 2]

I want to get [[email protected], [email protected], [email protected]]. The _id is a mongoose ObjectId, but simplified in the example.

1
  • you can use in, here is sample p.find() .where("studentEmails") .in([1, 2]) Commented Oct 22, 2020 at 23:20

1 Answer 1

1

You can use the distinct method with condition for this.

Model.distinct(
  "studentEmails",
  { _id: { $in: [mongoose.Types.ObjectId("1"), mongoose.Types.ObjectId("2")] } },
  function (err, data) {
    if (err) {
      console.log(err);
    } else {
      console.log(data);
    }
  }
);
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.