简体   繁体   中英

Trying to save nested document in MongoDB using mongoose on Nodejs

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)

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM