Q:

How to join from two collections with these mongoose schema(Node Js)? 

I have 3 schemas.  My api in node js is to fetch user data according to questionnaire matchedUsers.  I have got success in that it is populating matched users data.  But, i also want to add ratings from rating schema in the result if ratingById is matchedusers Id.   
 const RatingSchema = new mongoose. Schema({
      ratingDate: {
        type: Date,
        required: true
      },
      ratedById: {
        type: mongoose. Schema. Types. ObjectId,
        ref: "User",
        required: true
      },
      ratingOfId: {
        type: mongoose. Schema. Types. ObjectId,
        ref: "User"
      },
      rating: {
        type: Number
      },
      ratingComments: {
        type: String
      },
    });

const QuestionnaireSchema = new mongoose. Schema({
  userId: {
    type: mongoose. Schema. Types. ObjectId,
    ref: "User"
  },

  matchedUsers: {
    type: [mongoose. Schema. Types. ObjectId],
    ref: "User"
  }
});

const UserSchema = new mongoose. Schema({
  type: {
    type: String
  },
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true
  }
});

Please help how can i add ratings data to the query.  My code is-
router.get("/:id/matches", (req, res, next) => {
  Questionnaires.findById(req.query.questionnaireId)
    .populate({ path: "matchedUsers", model: "User" })
    .exec()
    .then(questionnaire =>
      res.json({ success: true, matches: questionnaire.matchedUsers })
    )
    .catch(err => {
      console.log(err);
      return res.json({ success: false, message: "Could not get matches." }); 
    });
});

A:

You'll have to use aggregate for that in your query, and $lookup to get reference from another schema
First we get references of users from User Schema & then get reference of Rating for each user in Rating Schema
 Questionnaires.aggregate([
     {
         $match:{
             _id:req.query.questionnaireId
         }
     },{
         $lookup:{
             from:'users',
             localField:'matchedUsers',
             foreignField:'_id',
             as:'user'
         }
     },{
         $unwind:{
             path:'$user',
             preserveNullAndEmptyArrays:true
         }
     },{
         $lookup:{
             from:'ratings',
             localField:'user._id',
             foreignField:'ratingById',
             as:'rating'
         }
     },{
         $unwind:{
             path:'$rating',
             preserveNullAndEmptyArrays:true
         }
     }
 ]);

