Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Mongoose / MongoDB - Query by Array in another document

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
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do this with aggreagte and lookup

db.users.aggregate([    
    { $match: { _id: user.id }},
    { $unwind: "$projectIds"},
    { $lookup: { 
        from: ProjectModel.collection.name,
        as: "project",
        pipeline: [
            { $match: { _id: id }}
        ]
    }}
])
.map(doc => doc.project);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!