Home > database >  How can I parse from string json to object json and save MongoDB
How can I parse from string json to object json and save MongoDB

Time:09-10

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!

CodePudding user response:

There are a lot of things unknown so I am going to assume you are all good with the express setup and bodyParser in place. If not consider using it. It will help you to take care of the json parsing without the trouble of you parsing it manually in each endpoint.

ref: https://medium.com/@gohitvaranasi/how-to-use-body-parser-in-express-to-handle-different-post-requests-c58c29d45b46

console.log(req.body.answer) to see what actually you are getting in the answer field. you don't need to stringify and parse again.

const nanswer = JSON.parse(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
    };

CodePudding user response:

Usually what I do to post data from a form (using react-hook-form):

import { set, useForm } from "react-hook-form";

const Testimonials= () => {
const { register, formState: { errors }, handleSubmit } = useForm();
const onSubmit = async (data) => {
//here the data give you an array of object
        await fetch('url', {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
            },
            body: JSON.stringify(data)
        })
    }

 return (
  <form onSubmit={handleSubmit(onSubmit)}>

       <textarea style={{ backgroundColor: '#e8e7e9', border: '#0c0c0c' }}
                 id="review" name="review" rows="8"      
                  {...register("review")}>
        </textarea>
       <input className='btn bg-[#050535] w-full max-w-xs text-white my-3' 
         type="submit" value="Submit Review" />

 </form>);
};

export default Testimonials;
  • Related