Debug School

rakesh kumar
rakesh kumar

Posted on

How to renders data from two collection using aggregate operator in node js

To add a field from the second collection to the output in the myfeedback array, you can use the $addFields stage in the aggregation pipeline. Here's an updated version of your code to include a field from the second collection:

try {
  const myfeedback = await FeedbackModel.aggregate([
    {
      $match: { questionid: number }
    },
    {
      $lookup: {
        from: 'users',
        localField: 'email',
        foreignField: 'email',
        as: 'joinedData'
      }
    },
    {
      $addFields: {
        joinedField: { $arrayElemAt: ['$joinedData.fieldName', 0] }
        // Replace 'fieldName' with the actual field name from the 'users' collection you want to include
      }
    }
  ]).exec();

  return myfeedback;
} catch (error) {
  // Handle the error
  console.error(error);
  throw error;
}
Enter fullscreen mode Exit fullscreen mode

Image description

In this code:

After the $lookup stage, the $addFields stage is added to the aggregation pipeline.

Inside the $addFields stage, you can use the $arrayElemAt operator to access a specific field from the joinedData array. Replace 'fieldName' with the actual field name from the 'users' collection that you want to include.

The joinedField is added to each document in the myfeedback array, containing the value of the specified field from the second collection.

Make sure to replace 'fieldName' with the actual field name from the 'users' collection that you want to include.

By including the $addFields stage in the aggregation pipeline, you can add the desired field from the second collection to each document in the myfeedback array. This updated myfeedback array can then be returned and used in your application.

=============================================
I have two collection
feedback and users
i want to get all field from feedbacks collection
and one field name from users collection
users collection
Image description

feedback collections

Image description

Image description

In server side

const getMyReviewReport = async (req, res) => {
  console.log("yanha aata getMyReviewReport",typeof req.params.item)

  // console.log(req.params.item);
 const item=req.params.item
 const number=Number(item);
 console.log(number);
//  const myfeedback = await FeedbackModel.find({ questionid: item }).exec();  

    try {
      const myfeedback = await FeedbackModel.aggregate([
        {
          $match: { questionid: number }
        },
        {
          $lookup: {
            from: 'users', 
            localField: 'email',
            foreignField: 'email',
            as: 'joinedData'
          }
        },
        {
          $addFields: {
            name: { $arrayElemAt: ['$joinedData.name', 0] }
            // Replace 'fieldName' with the actual field name from the 'users' collection you want to include
          }
        }
        // {
        //   $project:{
        //     joinedData:1
        //   }
        // }
      ]);  
      console.log(myfeedback); 
      const mydata = await FeedbackModel.find({ questionid: item }, { email: 1, _id: 0 }).exec();
     const emails = mydata.map((obj) => obj.email);
      console.log(emails);    
      const feedbacks = await User.find({ email: { $in: emails } }, { name: 1, _id: 0 }).exec();
      const feedback = feedbacks.map((obj) => obj.name);
      console.log(feedback);
      res.status(200).json({ myfeedback ,feedback: feedback})  
      } catch (error) {
        // Handle the error
        console.error(error);
        throw error;
      }


}

Enter fullscreen mode Exit fullscreen mode

In client side

Image description

 return (
    <Wrapper>
      <div className="row">
        <div className="col-md-4">
          <div className="box">
            <h5>Question</h5>
            {questions.map((item) => (
              <tr key={item.id}>
                <td onClick={() => getFeedback(item.questionid)}  className={activeCell === item.questionid ? 'active' : ''}  >{item.question}  </td>
              </tr>
            ))}
          </div>
        </div>
        <div className="col-md-8">
          <div className="box-dash">
            <h5>Total Feedback:{myfeedback?myfeedback.length:null} </h5>
            <div>
              {myfeedback ?
                myfeedback.map((item) => (
                  <div key={item.id} className="feedbox">                   
                    <h7><b>Name:</b></h7>
                    <p>{item.name}</p>
                    <h6><b>Options:</b></h6>   
                   <ul><li>{item.answer_one}</li>
                      <li>{item.answer_two}</li>
                      <li>{item.answer_three}</li>
                      <li>{item.answer_four}</li></ul>
                      <h6><b>Sentiments:</b></h6> 
                    <div className="d-flex">                   
                      <p>{item.sentiment}({item.score})</p>                     
                    </div>
                  </div>
                ))
                : <p>No feedback data available</p>}  
          </div>
        </div>
      </div>
</div>
    </Wrapper>
  );
Enter fullscreen mode Exit fullscreen mode

json form

Image description

Image description

Top comments (0)