Use Populate to Join Queries
Mongoose supports join queries by doing mutliple queries. Note: State of collections in the database can change during the join query.
usersRouter.get('/', async (request, response) => { const users = await User.find({}).populate('blogs', { title: 1, author: 1, url: 1 }) response.json(users)})
Example output:
[ { "blogs": [ { "title": "Whatthefuck.is", "author": "Dan Abramov", "url": "https://whatthefuck.is/", "id": "5f1927587228728f020a705a" }, { "title": "Josh Branchaud", "author": "Josh Branchaud", "url": "https://dev.to/jbranchaud", "id": "5f1928427228728f020a705b" } ], "username": "mburham", "name": "Michael Burham", "id": "5f18c2a4092dee858862166f" } ]
blogsRouter.get('/', async (request, response) => { const blogs = await Blog.find({}).populate('user', { username: 1, name: 1 }) response.json(blogs)})
Example output:
[ { "likes": 0, "title": "Josh Branchaud", "author": "Josh Branchaud", "url": "https://dev.to/jbranchaud", "user": { "username": "mburham", "name": "Michael Burham", "id": "5f18c2a4092dee858862166f" }, "id": "5f1928427228728f020a705b" }, { "likes": 0, "title": "Life at the bleeding edge(of web standards)", "author": "Lea Verou", "url": "https://lea.verou.me/", "user": { "username": "hobbes", "name": "Hobbes the cat", "id": "5f188925e811ec705b7525a5" }, "id": "5f192be8837fa0918991877c" },]
Source -> Mongoose: Populate method