Link data in Mongodb

Asked

Viewed 140 times

0

Model

    const AvaliacaoShema = new Schema({

    responsavel: {
        type: String,
        required: true
    },

    time: {
        type: Schema.Types.ObjectId,
        ref: 'Time',
        required: true
    },

    pergunta: [{
        type: Schema.Types.ObjectId,
        ref: 'Pergunta',
        required: true,
    }],

    Resposta: [{
        type: Schema.Types.ObjectId,
        ref: 'Resposta',
        required: true
    }],    

}, {
    timestamps: true
})
module.exports = model('Avaliacao', AvaliacaoShema)


const Avaliacao = require('../models/Avaliacao')

Controller

module.exports = {
    async index(req, res) {
        await Avaliacao.find(req.body)
            .populate('pergunta')
            .populate('getResposta')
            .exec()
            .then((a) => res.json(a))
            .catch(err => console.log(err))
    },

    async show(req, res) {
        await Avaliacao.findById(req.params.id)
            .populate('pergunta')
            .populate('getResposta')
            .exec()
            .then((a) => res.json(a))
            .catch(err => console.log(err))
    },

    async create(req, res) {
        try {
            const avali = await Avaliacao.create(req.body)
            return res.json(avali)
        } catch (error) {
            res.status(500).send({ error })
        }
    },

    async edit(req, res) {
        const avali = await Avaliacao.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true })

        return res.json(avali)
    },
    async delete(req, res) {
        await Avaliacao.findByIdAndDelete(req.params.id)

        return res.send()
    }}

Good morning guys, I’m doing a questionnaire system, which the admin adds to the discipline that respectively has questions from her, I have a Collection of questions that contains discipline + questions, I made a answer Collection, which has options like Yes, No and Does Not Apply, in this on screen is the evaluation that has to save question and answer, is saving _id of the question and _id of the answer, but is not linking them, as I do to link the question with the answer, because in the end I need to make a calculation,

Thanks.

1 answer

1


I think I understand your problem better, it’s in the modeling of your schema.

The Schema.Types.ObjectId is used to reference another schema, not auto-referencing in the same schema. For this you would have to use each schema specifically for each one.

One for user, one for question and one for answer.

In your question you put that:

  1. I have a Committee of Questions with discipline + questions

  2. made a reply Collection, which has options like Yes, No and Does Not Apply

  3. in this on screen Collection is the evaluation that has to save question and answer, is saving _id of the question and _id of the answer, but is not linking it

You made a schema (a model) called Avaliacoes containing the items pergunta and resposta, to do what you want, you need to separate each of them into separate files.

Appraisal - Create the evaluation schema and collect from others. If you want you can refer the responsible to a teacher.

/**Local onde está seu conector do banco.*/
const mongoose = require('../../database/mongodb')

const Avaliacao = new mongoose.Schema({

    responsavel: {
        type: String,
        required: true
    },

    pergunta: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Pergunta',
        required: true,
    }],

    Resposta: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Resposta',
        required: true
    }],   

}, {
    timestamps: true
})

const Avaliacao = mongoose.model.('Avaliacao', AvaliacaoSchema)
module.exports = Avaliacao

Question - question schema

/**Local onde está seu conector do banco.*/
const mongoose = require('../../database/mongodb')

const PerguntaSchema = new mongoose.Schema({

    /**Campos do que você quiser para a pergunta*/

})

const Pergunta = mongoose.model.('Pergunta', PerguntaSchema)
module.exports = Pergunta

Answer - response schema. You can reference a student here.

/**Local onde está seu conector do banco.*/
const mongoose = require('../../database/mongodb')

const respostaSchema = new mongoose.Schema({

    /**Campos do que você quiser para a pergunta*/

})

const Resposta = mongoose.model.('Resposta', respostaSchema)
module.exports = Resposta

Controller In your controller, you would need to go through each question and answer to then assign to evaluations, making the code for evaluation to receive the questions in one method postwith a async:

await Promise.all(perguntas.map(Pergunta => {
    const avaliacaoPergunta = new Pergunta({ ...pergunta, avaliacao: avaliacao._id })

await avaliacaoPergunta.save()

avaliacao.perguntas.push(avaliacaoPergunta)
}))

await avaliacao.save()

return res.send({ avaliacao })

For popular, you can do in a method get with a async, can be done in the listing and single record:

const avaliacoes = await Avaliacao.find().populate(['perguntas'])

return res.send({ avaliacoes })

Do the same for the answers and be happy.

I believe this is it, no?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.