'Find all users that have the same reference objects -- mongoose
I have a users with an array of references to another model (sport). Now I want to create a GET route to find users who have common references with one specific user. I just cant figure out, how to do it...... would be great if someone can help :) I tried something like...
router.get("/matches", (req, res) => {
const { _id } = req.payload;
User.findById(_id)
.then((currentUser) => {
currentUser.sports.map((sportDetails) => {
sportDetails.map((sportId) => {
const {_id} = sportId
})
return User.find({ sports: { sportId } });
});
})
.then((matches) => {
res.json(matches)
})
.catch((err) => {
console.log("no matches...", err)
})
});
user.model
const userSchema = new Schema(
{
username: String,
sports: [{ type: Schema.Types.ObjectId, ref: "Sport" }]
}
);
sport.model
const sportSchema = new Schema(
{
title: String,
level: String
}
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
