MongoDB обновляет ссылки

#javascript #node.js #mongodb #express #mongoose

#javascript #node.js #mongodb #экспресс #мангуст

Вопрос:

пожалуйста, мне нужна помощь в создании функции обновления в assignmentsController, я хочу, чтобы пользователь мог создать назначение, тогда я смогу создать тест внутри назначений и вернуть его. например, это то, что я хочу вернуть после обновления раздела викторины назначения. { "quiz": [{question:""this is a sample question?", "correct_answer":"sample correct", "incorrect_answers: ["wrong", "not correct"], "createdAt": "2020-12-10T00:50:27.932Z", "_id": "5fd170d6712a647ad072c449", "title": "what are you?", }

Это функция обновления

 export const updateAssignments = async (req, res) => {
    const { id } = req.params;

    const {title} = req.body;
    
    if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No Asssignment with id: ${id}`);

    const updatedPost = {title,_id: id, $push: { quiz:[{$each: updatedquiz} ]}};
    
    // await Assignment.findByIdAndUpdate(assignmentId)
    await Assignments.findByIdAndUpdate(id, updatedPost, { new: true });

    res.json(updatedPost);
}

 

это все файлы

 **Assignment.js**


import mongoose from 'mongoose'

const AssignmentsSchema = new mongoose.Schema({
    
    title: String,
    quiz: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Quiz"
    }],
    createdAt: {
        type: Date,
        default: new Date(),
    },

    
});

const Assignments = mongoose.model("Assignments", AssignmentsSchema)
export default Assignments;


`

 - **Quiz.js**

 import mongoose from 'mongoose';

const QuizSchema = mongoose.Schema({
    question: String,
    correct_answer: String,
    incorrect_answers: [],
    assignments: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Assignments"
    },
})

var Quiz = mongoose.model('Quiz', QuizSchema);

export default Quiz;



**AssignmentsController.js**


import express from 'express';
import mongoose from 'mongoose';

import Assignments from '../models/Assignments.js';
import Assignment from '../models/Quiz.js';

const router = express.Router();

export const getAssignments = async (req, res) => { 
    try {
        const postAssignment = await Assignments.find().populate('quiz');
                
        res.status(200).json(postAssignment);
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

export const getAssignmentsById = async (req, res) => { 
    const { id } = req.params.id;

    try {
        const post = await (await Assignments.findById(id)).populate('quiz');
        
        res.status(200).json(post);
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

export const createAssignments = async (req, res) => {
    try { 

    const { title, createdAt} = req.body;



    
        const newAssignment = new Assignments({
                    title,
                    createdAt,
                    quiz: [req._id],
                    
                });
                

                await newAssignment



                    .populate('quiz')
                    .execPopulate()
                    

                
                // newAssignment.assignmentQuestion = newAssignment.assignment.question
                // newAssignment.assignmentDate = createdAt
                // newAssignment.correctanswer = registration.user.email
                newAssignment.save()

                
                res.status(201).json(newAssignment );
        
    } catch (error) {
        res.status(409).json({ message: 'does not work' });
    }

}

export const updateAssignments = async (req, res) => {
    const { id } = req.params;
    // const { quizid } = req.params;
    // const { question, correct_answer, incorrect_answers} = req.body;
    const {title} = req.body;
    
    if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No Asssignment with id: ${id}`);

    const updatedPost = {title,_id: id, $push: { quiz:[{$each: updatedquiz} ]}};
    
    // await Assignment.findByIdAndUpdate(assignmentId)
    await Assignments.findByIdAndUpdate(id, updatedPost, { new: true });

    res.json(updatedPost);
}
export const deleteAssignment = async (req, res) => {
    const { id } = req.params;

    if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No Assignment with id: ${id}`);

    await Assignment.findByIdAndRemove(id);

    res.json({ message: "Assignment deleted successfully." });
}



export default router;


**assignmentsRoute.js**

import express from 'express';

import { createAssignments, getAssignments, getAssignmentsById, updateAssignments } from '../controllers/AssignmentsController.js';

const router = express.Router();

//Assignment

router.get('/', getAssignments);
router.post('/', createAssignments);
router.get('/:assignment_id', getAssignmentsById);
router.patch('/:assignment_id/quiz', updateAssignments);
router.delete('/:assignment_id', deleteAssignment);


export default router;


**server.js**

import express from 'express'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import cors from 'cors'
import dotenv from 'dotenv'

import userRoutes from './routes/userRoute.js';
import quizRoutes from './routes/quizRoute.js'
import assignmentsRoutes from './routes/assignmentsRoute.js';
import loginRoutes from './routes/loginRoute.js';
import registrationRoutes from './routes/registrationRoute.js';



const app = express();

app.use(cors());

const PORT = process.env.PORT || 8001;

if(process.env.NODE_ENV !== 'production'){
    dotenv.config()
}
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }))

app.use('/user', userRoutes);
app.use('/login', loginRoutes);
app.use('/registration', registrationRoutes);
app.use('/quiz', quizRoutes);
app.use('/assignments', assignmentsRoutes);


mongoose.connect(process.env.MONGO_DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
  .catch((error) => console.log(`${error} did not connect`));
 

Ответ №1:

изначально я хотел создать задание, а затем добавить в него вопросы викторины, для этого мне нужно было изменить схему модели модели присваивания, чтобы вместо нее был массив тестов, ссылающихся на модель викторины. затем я выполнил метод $ push, и поэтому я могу добавить столько вопросов, сколько захочу.

Assignments.js

 import mongoose from 'mongoose'

const AssignmentsSchema = new mongoose.Schema({
    
    title: String,
    quizes: [{
        question:String,
        correct_answer:String,
        incorrect_answers:[]
    }],
    createdAt: {
        type: Date,
        default: new Date(),
    },

    
});

const Assignments = mongoose.model("Assignments", AssignmentsSchema)
export default Assignments;



then i created the addQuestion function in AssignmentController.js



`export const addQuestion = async (req, res) =>{
    const { id } = req.params;
    
    try {
       

       const addedQuestion = await Assignments.findByIdAndUpdate(

            {_id: id},
            { $push: { quizes: {$each: req.body.quizes}}},
            {safe: true, upsert: true, new : true}
        );`


this is the result 


{
_id:5fd83417c78f8dd70351c613
createdAt:2020-12-15T03:53:17.724 00:00
title:"first assignment"
quizes:Array
 {0:Object
   incorrect_answers:Array
  { 
    0:"wrong"
    1:"write"
    2:"ugly"
  }

_id:5fd83593106af1d8fa87b94c

   question:"this is question 1"
   correct_answer:"sample answer"
 {
  1:Object
  incorrect_answers:Array
 _id:5fd835a3106af1d8fa87b94d
  question:"this is question 2"
  correct_answer:"sample answer 2"
 {
   2:Object
   incorrect_answers:Array
  _id:5fd835ba106af1d8fa87b94e
   question:"this is question 3"
   correct_answer:"sample answer 3"
}

}
}