I need my Schema to receive an array with this structure:
const arrayAnswers: [
{description: 'String', isCorrect: true},
{description: 'String', isCorrect: false},
{description: 'String', isCorrect: false}
]
This is the schematic I write:
const mongoose = require('mongoose');
const {Schema} = mongoose;
const fields = {
answers: [Object]
}
const question = new Schema(Object.assign(fields), {timestamps: true});
module.exports = {
Model: mongoose.model('question', question),
fields
};
Can the schema for that field be like this or is there something wrong with it [Object]
?
I have read about Schema.Types.Mixed
and about subdocuments, but I wouldn't know how to make the subdocument. And according to the Mixed makes it lose the ability to autodetect and save changes, so I don't know what repercussions it can have exactly with what I do.
Of course you can. If the structure of the object you are going to store in your field
answers
is fixed, then you can do something like the following:What we have done is define the field
answers
as a typearray
and inside we have established the structure of the type of document it will contain. I have used constraintsrequired
on the document fields, although you may not need them, that will depend on your logic.Doing it the way you intend (according to what you state in your question) would make the data type stored in the field the default
answers
type .Mixed
You can read more about the
Array
Mongoose type in the documentation .I hope this helps you solve your doubt.