0

Im trying to save a data to database once the user is found yet not sucsssful

const Profile = require("../../models/Profile");
const User = require("../../models/User");

router.post('/profile',(req,res) => {

        User.findOne({
            "_id": id
        }).then(user => {
            if (!user) {
                return res.status(400).json({
                    email: "User not found"
                });
            } else {
               const newProfile = new Profile({
                    companyname: req.body.companyname,
                    userid: user._id
                 });

               newProfile.save().then((user) => {
                    res.json(user)
                 }).catch(err => console.log(err));

               res.send(newProfile)
           }
        }).catch(err => {
            return res.status(400).json({
                    message: "User not found"
                });
        });
})

I was expecting for the data to be saved in profile collection(not user collection) yet I am getting an error message as follows

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/Users/guest/Desktop/mernapp/node_modules/express/lib/response.js:775:10)
    at ServerResponse.send (/Users/guest/Desktop/mernapp/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/Users/guest/Desktop/mernapp/node_modules/express/lib/response.js:271:15)
    at newProfile.save.then (/Users/guest/Desktop/mernapp/routes/api/profile.js:59:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
WSMathias9
  • 669
  • 8
  • 15
moytoy
  • 7
  • 3

1 Answers1

0

res.send(newProfile) need to remove. I have updated code, hope it's helpful.

router.post('/profile',(req,res) => {
    User.findOne({
        "_id": id
    }).then(user => {
        if (!user) {
            return res.status(400).json({
                email: "User not found"
            });
        } else {
            const newProfile = new Profile({
                companyname: req.body.companyname,
                userid: user._id
            });
            newProfile.save().then((newProfileRes) => {
                res.status(200);
                res.json(newProfileRes);
            }).catch(err => {
                console.log(err);
                res.json({message : 'Profile not Created'});
            });
        }
    }).catch(err => {
        return res.status(400).json({
                message: "User not found"
            });
    });
})
the_mahasagar
  • 1,201
  • 2
  • 16
  • 24