Is there a way to make a query dependent on another document from another schema in mongoose?
Say I have a user with a list of projects and I want to find a project by ID only if the provided user has the projectId in its list of projects.
Project Schema (extends from Document):
const projectSchema = new Schema<ProjectSchema, ProjectModel>(
{
name: { type: String, required: true, trim: true },
description: { type: String, default: '', trim: true },
},
{
collection: 'project',
timestamps: true,
versionKey: false,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
User Schema (extends from Document):
const userSchema = new Schema<UserSchema, UserModel>(
{
email: { type: String, unique: true, required: true, trim: true },
projectIds: { type: [Schema.Types.ObjectId], default: [], ref: 'Project' },
},
{ collection: 'user', timestamps: true, versionKey: false },
);
So I would like to get the project that has the ID and which in the database is within the projectIds array of the user.
export async function findProjectForUser(user: User, id: string) {
// get the user from DB by user id (security reasons)
const dbUser = await UserModel.findById(user.id);
if(!dbUser) return undefined; // 401
// check if user has id in projectId array
const hasProject = dbUser.projectIds.find(pId => pId === id);
if(!hasProject) return undefined // 401
// fetch project from db by id
const project = await ProjectModel.findById(id);
// => can I merge the two queries into one?
return project
}