1

My first time on the platform. I am learning to code and one of the tasks I need to accomplish is to build a route utilizing Mongoose/MongoDB from a node/express server app so I may update the object data. I have had success in utilizing postman to query simple objects but am having issues querying child or nested documents (still trying to command the right terminology so bear with me). I have two schemas, one describing the parent object, and the second describing the child/nested object that is stored as an array. I have built a route that so far returns the parent object, but I have been unable to find documentation (that I can follow) that explains how to acquire the nested object. I have tried to use js functions to query the full object, set a local variable with the intent of overwriting it. But I feel like there is a "more righter" answer to the problem.

Here is my Schema

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

Here is my route

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}`);
        //   }
});

The end there is my experimenting/incomplete code to try and access the child object. so I know it is wrong. returns in postman up to this linke "const question = await Question.findById("

And here is my set up:

 "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"
  

This is a pattern that will show up repeatedly so I am hoping to see a proper way to do this I can both learn from and recreate. Thank you in advance for any ideas or tips!

  • dose this code work?? I think there are many bugs in your code – Mohammad Yaser Ahmadi Feb 03 '21 at 19:06
  • no it does not. In my explanation (probably not very well) tried to explain that if I comment out the lower part of the route, it will return the full object. I want to pull in the object by ID and then update the child object...somehow – Richard Marshall Feb 03 '21 at 20:22

0 Answers0