I'm trying to parse data json when submit form in Nodejs. With schemas MongoDB as:
const QuestionSchema = new mongoose.Schema({
_id:Number,
isCat:Number,
Question: String,
Answer:Array,
img:
{
data: Buffer,
contentType: String
},
isCorrect:Number
});
I want to save Answer the same as: [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]. With submit form as:
<form action="/" method="POST" enctype="multipart/form-data" id="form-driver">
<div>
<label for="name">Question:</label>
<input type="text" id="question" placeholder="Name"
value="" name="question" required>
</div>
<div>
<label for="desc">Ansers</label>
<textarea id="answer" name="answer" value="" rows="2"
placeholder="Description" required>
</textarea>
</div>
<div>
<label for="image">Upload Image</label>
<input type="file" id="image"
name="image" value="" required>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
And function to create object which save into MongoDB AS:
var nanswer = null;
nanswer= JSON.parse(JSON.stringify(req.body.answer));
const obj={
_id:parseInt(await QuestionModel.countDocuments()) + 1,
isCat:0,
Question:req.body.question,
Answer:[nanswer],
img: {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
contentType: 'image/png'
},
isCorrect:0
};
But value when I submit form for field Answer it was a array string not array object as: ["{id:1,name:'a'},{id:2,name:'b'}"] How I can do that? Please help me to fix it. Thanks so much!