0

I was trying to save address as nested document in below format

On client side I was sending the data in below format:

const address = JSON.stringify( { addressline1:form.addressline1.value, addressline2:form.addressline2.value, city: form.city.value, state: form.state.value, pincode:form.pincode.value } );

const res = await fetch('/candidate/contact-details',{
                method: 'POST',
                body: JSON.stringify( { address } ), 
                headers: {
                    'CSRF-Token': csrfToken,
                    'Content-Type': 'application/json'
                }
            });

on Server side :

module.exports.contactdetail_post = async (req,res) => {

    const token = req.cookies.jwtauthtoken;
    const { address} = req.body;

    try{
        const contactdetail = await ContactDetail.create({ address});
        await PersonalDetail.findOneAndUpdate(
            { candidate: await getUserId(token)}, // find a document with that filter
            {address}, // document to insert when nothing was found
            {upsert: true, new: true, runValidators: true}, // options
            function (err, doc) { // callback
                if (err) {

    console.log({address});
                    const errors = handleErrors(err);
                } else {
                    res.status(200).json({success: 'saved'});
                }
            }
        );
        res.status(200).json({ success: 'Success' });
    }
    catch(err){
        console.log(err);
        const errors = handleErrors(err);
        res.status(406).json({errors});
    }




}

MySchema looks like this: This is the schema of the contact detail.

const contactdetailSchema = new mongoose.Schema({
    address: {
        addressline1: {
            type: String,
            required: [true, 'Please enter your address'],
            minlength:200
        },
        addressline2: {
            type: String,
            minlength:200
        },
        city: {
            type: String,
            required: [true, 'Please selet your city']
        },
        state: {
            type: String,
            required: [true, 'Please select your state']
        },
        pincode: {
            type: Number,
            required: [true, 'Please enter your Pincode'],
            minlength:6
        }
    },
    candidate: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
});

my console output:

at processTicksAndRejections (internal/process/task_queues.js:79:11) { properties: [Object], kind: 'required', path: 'address.addressline1', value: undefined, reason: undefined, [Symbol(mongoose:validatorError)]: true } }, _message: 'Validation failed' }

this error shows for all the parameters ( addressline2, city, state,pincode)

3
  • 1
    I don't see you parsing the JSON anywhere here in the code. You stringify it on the client, but if you do that, then you need to JSON.parse() it on the server. Ideally, you shouldn't be stringifying it at all. The error you're receiving is valid, as the server just sees one big string rather than the JSON data that it is expecting. Commented Sep 18, 2020 at 14:59
  • I used JSON.parse on address and stringifyed it on body but it shows following error. Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1. Can you specify exactly where to modify the code to get correct output. Commented Sep 19, 2020 at 4:59
  • Hey Thanks for your help. It works after I changing the code { address: JSON.parse(address) } inside the findOneAndUpdate(). Commented Sep 19, 2020 at 5:21

1 Answer 1

1
 await PersonalDetail.findOneAndUpdate(
            { candidate: await getUserId(token)}, // find a document with that filter
            {address: JSON.parse(address) }, // This line is changed 
            {upsert: true, new: true, runValidators: true}, // options
            function (err, doc) { // callback
                if (err) {

    console.log({address});
                    const errors = handleErrors(err);
                } else {
                    res.status(200).json({success: 'saved'});
                }
            }
        );

Changing my code like this works fine. Other code remains the same

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.