Home > OS >  Match fields from 2 different collection and display result based on the match mongodb nodejs
Match fields from 2 different collection and display result based on the match mongodb nodejs

Time:03-29

I have 2 collection one is user and one is questions. both has common field type. If user type matches with type in questions then the result will be displayed.

const questionsSchema = mongoose.Schema({
    question: { type: String },
    number: { type: Number },
    usertype: {
        type: String,
        enum: ['A' , 'B'],
    },
},{ timestamps: true });

const usersSchema = mongoose.Schema({
    name: { type: String },   
    type: {
        type: String,
        enum: ['A', 'B']
    },
}, { timestamps: true }
);

I want to make a query to fetch questions based on user type. If user type matches then the desired set of questions will be displayed.

This is my question.js file

    export const fetchQuestions = async (req, res) => {
      try {
        const user = await db.findOne('USER', { _id: req.userId });
        
        const type = user.type;
        console.log(type   "user type");
        let answerdQuestions = [];
        let nextQuestions;
        let quiz;
        if (user.quiz) {
          quiz = await db.findOne('QUIZ', { user: req.userId });
          answerdQuestions = quiz.responses.map(response => response.number)
        }
        nextQuestions = getNextQuestions(answerdQuestions);
 // Here I have place query to fetch usertype questions.
        const questions = await db.find('QUESTION', { number: { $in: nextQuestions } });
        res.status(200).json({ questions, quiz: { id: quiz?._id, responded: answerdQuestions.length }, options: options });
        return answerdQuestions;
      } catch (err) {
        console.log(err)
        res.status(500).json({ message: "Something went wrong" });
      }
    };

 

Any help is appreciated.

CodePudding user response:

You just have to fetch questions by usertype. So, use this query:

// Here I have place query to fetch usertype questions.
const type = user.type;
const questionsByUserType = await db.find('QUESTION', { usertype: type });

Just find all the questions from questionsSchema where usertype property matches type property which was derived from usersSchema.

  • Related