For example I have two models
const User = new Schema({
name: { type: String },
});
const Message = new Schema({
user: { type: ObjectId, ref: 'User' },
message: { type: String },
});
How to find messages by the key "name" in the user?
It doesn’t work
exports.get = async (req, res) => {
return Message.find({ "user.name": req.query.name })
.populate('user', 'name')
.then((data) => res.json(data));
}
I understand why "user.name" doesn’t work, but I don’t know how to solve it
3
Answers
You would want to use $lookup -> unwind -> match:
Unwind: convert user array to user object from look up stage
There is no concept of a join in Mongodb. Hence I would recommend using straight schema definition like this:
then you wouldn’t need to use
populate
anymore. Instead, you would have something like this:However, If you still prefer to use the current approach, You can try this:
Basically you need the correct ordering of table
User must be your primary table and Messages must be your secondary table from which you should lookup.
The query is as following;
}
This will return all the messages as an array with field name messages of "name" person e.g;