Home > Mobile >  Nodejs express Converting circular structure to JSON
Nodejs express Converting circular structure to JSON

Time:10-03

I have images in array and I am updating in database. But issue its showing this error

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'MongoClient'

And this is my code

const updateCompany = async (req, res) => {
    const file = req.files;
    if (!file) return res.status(400).send('No image in the request');
    const companyLogoName = file[0].filename;
    const companyImageName = file[1].filename;

    const basePath = `${req.protocol}://${req.get('host')}/public/uploads/`;
    // console.log(`${basePath}${companyLogoName}`);
    // console.log(`${basePath}${companyImageName}`);

    try {
        const updateCompany = Company.findByIdAndUpdate(req.params.id, {
            companyName: req.body.companyName,
            companyDescription: req.body.companyDescription,
            companyWebsite: req.body.companyWebsite,
            companyDHeadQuater: req.body.companyDHeadQuater,
            companySpecialities: req.body.companySpecialities,
            companyFounded: req.body.companyFounded,
            companyIndustry: req.body.companyIndustry,
            companyMinEmploye: req.body.companyMinEmploye,
            companyMaxEmploye: req.body.companyMaxEmploye,
            companyType: req.body.companyType,
            companyLogo: `${basePath}${companyLogoName}`,
            companyImage: `${basePath}${companyImageName}`,

        }, {
            new: true
        });
        // console.log(updateCompany);

        return res.status(200).json({ success: true, data: updateCompany })
    } catch (err) {
        console.log(err);
        if (err.name === 'ValidationError') {
            console.error(Object.values(err.errors).map(val => val.message))
            return res.status(400).json({ success: false, message: Object.values(err.errors).map(val => val.message)[0] })
        }
        return res.status(400).json({ success: false, message: err })
    }
};

In console its showing correct path of images means multer file etc is working but issue is on update

CodePudding user response:

You aren't passing any callback function to findByIdAndUpdate, neither are you using await. According to the mongoose doc, findByIdAndUpdate will return an instance of Query object if no callback is passed. So updateCompany is actual an instance of Query object which express is trying to render as json and that's why the error at this line:

return res.status(200).json({ success: true, data: updateCompany })

You could either use await or add a callback function as specified in the doc.

  • Related