我有 2 個集合,一個是用戶,一個是問題。兩者都有共同的欄位型別。如果用戶型別與問題型別匹配,則將顯示結果。
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 }
);
我想根據用戶型別進行查詢以獲取問題。如果用戶型別匹配,則將顯示所需的一組問題。
這是我的 question.js 檔案
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" });
}
};
任何幫助表示贊賞。
uj5u.com熱心網友回復:
您只需要按用戶型別獲取問題。所以,使用這個查詢:
// Here I have place query to fetch usertype questions.
const type = user.type;
const questionsByUserType = await db.find('QUESTION', { usertype: type });
只需找到來自questionsSchemawhere屬性與派生自的usertype屬性匹配的所有問題。typeusersSchema
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451603.html
下一篇:上傳單個檔案mongoDb
