【问题标题】:How to properly use references in mongoose如何在猫鼬中正确使用引用
【发布时间】:2021-03-18 18:25:55
【问题描述】:

我正在尝试在 mongoose 中使用引用,但不知何故无法正确执行。

我正在努力实现的目标

我想查询examModel 并获取有关特定考试的所有信息,包括与该考试相关的问题。

我的成就

新问题被保存到questionModel 中,考试的对象ID 正在保存问题,但是examModelquestions 数组没有注意到它。

我有两种不同的型号:

examModel

const examSchema = new mongoose.Schema({
    examId: {
        type: String,
        unique: true,
        index: true,
        required: true,
        default: _generateAlphanumericId(18),
    },
    questions: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Questions",
    }],
}, {
    timestamps: true,
});

module.exports = mongoose.model("Exams", examSchema);  

问题模型

const questionSchema = new mongoose.Schema({
    _refExamId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Exams",
    },
    questionId: {
        type: String,
        unique: true,
        index: true,
        required: true,
        default: _generateAlphanumericId(26),
    },
    title: {
        type: String,
        trim: true,
        required: [true, "Question is missing"],
    },
}, {
    timestamps: true,
});

module.exports = mongoose.model("Questions", questionSchema);  

现在,当我将新问题保存到问题模型中时,我会从考试模型中发送考试的_id,但exam modelquestions 数组仍然不会保存新创建问题的对象ID .

我如何创建一个新问题

    try {
        const question = new questionModel({ _refExamId: req.body._refExamId, title: req.body.title });
        await question.save();

        return res.status(200).json({ type: "SUCCESS" });
    }
    catch (error) {
        return res.status(500).json({
            type: "ERROR",
            message: "Some unknown error occurred",
        });
    }  

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    首先,

    考试模式

    常量examSchema = new mongoose.Schema({ 考试编号:{ 类型:字符串, 独特的:真实的, 指数:真, 要求:真, 默认值:_generateAlphanumericId(18), }, 问题: [{ 类型:mongoose.Schema.Types.ObjectId, 参考:'问题' }], }, { 时间戳:真, }); module.exports = mongoose.model("考试",examSchema);

    注意:我将 Exams 转为 Exam,Mongodb 会在您的数据库中将其更改为复数

    问题模型

    const questionSchema = new mongoose.Schema({ _refExamId:{ 类型:mongoose.Schema.Types.ObjectId, 参考:“考试”, }, 问题ID:{ 类型:字符串, 独特的:真实的, 指数:真, 要求:真, 默认值:_generateAlphanumericId(26), }, 标题: { 类型:字符串, 修剪:真的, 必需:[true, "问题丢失"], }, }, { 时间戳:真, }); module.exports = mongoose.model("问题", questionSchema);

    注意:我将 Questions 转为 Question,Mongodb 会在您的数据库中将其更改为复数

    创建一个新问题

    尝试 { const question = new questionModel({ _refExamId: req.body._refExamId, title: req.body.title }); 等待问题。保存(); 返回 res.status(200).json({ type: "SUCCESS" }); } 捕捉(错误){ 返回 res.status(500).json({ 类型:“错误”, message: "发生了一些未知错误", }); }

    试试看吧

    【讨论】:

    • 试过了。它仍然是一样的。 :(
    • 但是它是作为空值保存到数据库还是出现错误?如果有错误,请与我们分享
    • 同时注释掉 req.body._refExamId 以确保它到达您的 API
    • 问题被正确保存。就是这样,考试模式的问题数组没有所创建问题的任何对象 ID。
    • 是的,没有错误,只是考试模式中的问题数组即使在向问题模型中添加了问题后仍保持空白
    【解决方案2】:
    尝试 { const question = new questionModel({ _refExamId: req.body._refExamId, title: req.body.title }); const saved_question = 等待问题.save(); const getExam = await ExamModel.find({_id: saved_question._refExamId}); getExam.questions.push(saved_question._id); 常量结果 = 等待 getExam.save(); 返回 res.status(200).json({ type: "SUCCESS" }); }捕捉(错误){ 返回 res.status(500).json({ 类型:“错误”, message: "发生了一些未知错误", }); }

    这应该可以正常工作。

    【讨论】:

    • 当然。 _refExamId 是来自 Exam 表中已存在的一项检查的对象 ID。
    • 那么您现在想要的是,每当您创建一个新问题时,您都希望将 question_id 推送到考试表的 _refExamId.question 数组中,对吧?
    • 根据文档,似乎我不需要明确推送任何内容,除非我需要将考试的对象 ID 发送到问题模式中。但是在遵循文档时,它似乎没有发生,所以除非我明确推送到考试模式
    • 这就是它的工作原理。需要我发送代码示例吗?
    • 检查上面的代码。我刚刚纠正了它。它应该工作
    【解决方案3】:

    所以,我没有阅读文档的 refs-to-children 部分,其中指出,除非我们明确将引用推送到父架构,否则父架构中不会有引用。

    因此,以下解决了我的问题:

        try {
            const exam = await examModel.findOne({ examId: req.body.exam_id });
            const question = new questionModel({ title: req.body.title, positiveMarks: req.body.positiveMarks });
            exam.questions.push(question);
            await exam.save(question.save());
    
            return res.status(200).json({ type: "SUCCESS" });
        }
        catch (error) {
            return res.status(500).json({
                type: "ERROR",
                message: "Some unknown error occurred",
            });
        }
    

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 2013-07-10
      • 2019-09-16
      • 2017-09-11
      • 2020-11-08
      • 1970-01-01
      相关资源
      最近更新 更多