Say I have a list of users. A user has
username,
email,
password,
sketches
sketches is another collection, and a sketch has
title
author
If I want to fetch a user with his/her sketches, I have to use aggregate to find all sketches that have author as his/her username.
This is working great:
const data = await userModel
.aggregate([
{ $match: { username } },
{ $lookup: { from: 'sketches', localField: 'username', foreignField: 'author', as: 'sketches' } },
{ $limit: 1 }
]).toArray()
The issue is that some users don't have sketches; when a user has no sketches, the aggregate does not return anything else about the user, so username, email, and password becomes undefined.
Is there any way I can make aggregate sort of optional? Like find the user and then try to see if they have any sketches.
Thanks!