const saveUserData = async (req, res, next) => { try { if (!Array.isArray(req.body.users)) { return res.status(400).json({ message: 'Invalid input format' }); } const results = []; const errors = []; for (const user of req.body.users) { try { const saveUser = new saveuser({ email: user.email, password: user.password, }); const savedUser = await saveUser.save(); const userID = savedUser._id; const saveDetail = new saveUserDetails({ user_id: userID, name: user.name, phone: user.phone, country: user.country, file: user.file.filename, }); const savedDetail = await saveDetail.save(); results.push({ status: 'success', user: savedUser, details: savedDetail, }); } catch (error) { if (user.file && user.file.path && fs.existsSync(user.file.path)) { fs.unlinkSync(user.file.path); } if (error.name === 'ValidationError') { const validationError = {}; for (const key in error.errors) { validationError[key] = error.errors[key].message; } errors.push({ user: user, error: validationError, }); } else { errors.push({ user: user, error: 'Server Error', }); } } } if (errors.length > 0) { return res.status(207).json({ results, errors }); } res.status(200).json({ results }); } catch (error) { res.status(500).json({ message: 'Server Error', }); } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter