I have a Schema Users that has a field manager of type mongoose.Schema.Types.ObjectId
that puts the id of a manager from another Schema that has other info about the manager. When i want to put the manager name in a result of a call to the User Schema i use a for loop as below:
const res = await axios.get('/api/users/all');
const config = {
headers: {
'Content-Type': 'application/json',
},
};
//adding planner name to the data
for (let element of res.data) {
element.plannerName = await axios.post(
'/api/planners/plannerName',
{ id: element.planner },
config
);
}
This works but i feel it is a slow solution. I am new to this field and i want to know if this is the best practice to do such task. Thank you!
What you are looking for is called join
in the database language.
You have to join user collection with manager collection. For doing this you can use populate()
function after find.
Here is the code:
let users = await User.find({}).populate('manager');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.