首页 > 解决方案 > 在 mongoose/node 中为嵌套的 mongo 对象构建路由

问题描述

我第一次上平台。我正在学习编码,我需要完成的任务之一是使用 Mongoose/MongoDB 从节点/快速服务器应用程序构建路由,以便我可以更新对象数据。我在利用邮递员查询简单对象方面取得了成功,但在查询子文档或嵌套文档时遇到了问题(仍在尝试使用正确的术语,所以请耐心等待)。我有两个模式,一个描述父对象,第二个描述存储为数组的子/嵌套对象。到目前为止,我已经构建了一个返回父对象的路由,但我一直无法找到解释如何获取嵌套对象的文档(我可以遵循)。我尝试使用 js 函数来查询完整对象,设置一个局部变量以覆盖它。但我觉得有一个“

这是我的架构

const mongoose = require("mongoose");
const Joi = require('joi');

const answerSchema = new mongoose.Schema({
  answerText: {type: String, required: false, minlength: 10, maxlength: 255},
  answerPoints: {type: Number},
  });
  
const Answer = mongoose.model('Answer', answerSchema);
  
function validateAnswer(answer) {
  const schema = Joi.object({
  answerText: Joi.string().min(10).max(255),
  answerPoints: Joi.number(),
  });
  return schema.validate(answer);
  }

const questionSchema = new mongoose.Schema({
  question: {type: String, required: true, minlength: 10, maxlength: 255},
  difficulty: {type: Number},
  category: {type: String, minlength:3},
  starred: {type: Boolean, default: false},
  dateModified: {type: Date, default: Date.now},
  start:{type: Date, default: Date.now},
  stop: {type: Date, default: Date.now},
  answers:[answerSchema],
});

const Question = mongoose.model('Question', questionSchema);

function validateQuestion(question) {
    const schema = Joi.object({
    question: Joi.string().min(10).max(255).required(),
    difficulty: Joi.number(),
    category: Joi.string().min(3),
    }).unknown();
    return schema.validate(question);
    }


    module.exports.Answer = Answer;
    module.exports.validateAnswer = validateAnswer;//this may cause an issue with line 47...changed to validateAnswer from validate
    module.exports.answerSchema = answerSchema; 

    module.exports.Question = Question;
    module.exports.validate = validateQuestion;
    module.exports.questionSchema = questionSchema

这是我的路线

router.put('/updateanswer/:id', async (req, res) => {
    // try{
    //     const{ error } = validate(req.body);
    //     if(error) return res.status(400).send(error);

        const question = await Question.findById(
            req.params.id, req.params.question,

        );
        let foundAnswerObject = question.answers.filter(function(element){
            if(element._id === req.params.id){
                return true;
            }
            else{
                return false;
            }
        });

        updateFoundAnswerObject() {
            foundAnswerObject = req.body.answerText,
        }
//possibly refactor with suchandsuch link
        //what other array functions are for finding one object?
        // if (!question)
        //     return res.status(400).send(`The comment with id "${req.params.id}" does not exist.`);

            await question.save();

            return res.send(question);
        //   } catch(ex) {
        //       return res.status(500).send(`Internal Server Error: ${ex}`);
        //   }
});

最后是我的实验/不完整代码来尝试访问子对象。所以我知道这是错误的。在邮递员中返回此链接“const question = await Question.findById(”

这是我的设置:

 "dependencies": {
    "bcrypt": "^5.0.0",
    "body-parse": "^0.1.0",
    "body-parser": "^1.19.0",
    "config": "^3.3.3",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "ejs": "^3.1.5",
    "express": "^4.17.1",
    "joi": "^17.3.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.11.13",
    "mongoose-type-email": "^1.1.2",
    "node": "^15.4.0",
    "nodemon": "^2.0.7",
    "path": "^0.12.7"
  

这是一种会反复出现的模式,所以我希望能找到一种正确的方法来做到这一点,我可以从中学习和重新创建。提前感谢您的任何想法或提示!

标签: node.jsexpressmongoosenested-routes

解决方案


推荐阅读