I have a collection in MongoDB and I am able to use get in Express to retrieve the data. But when make a put request to update from the client it works but mongooseInstance.save().then((err, settings) ... the promise returns the payload as the error variable.
Here is the code:
const SettingsSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
main_email: String,
bio: String,
gitHub_url: String,
linkedin_url: String,
bio_intro: String,
bio_tagline: String,
bio_pic: String
}),
SettingsModel = mongoose.model('profile_settings', SettingsSchema, 'profile_settings');
app.get('/profileSettings', (req, res) => {
SettingsModel.find((err, settings) => {
if (err) {
res.status(500).send(err);
} else {
res.json(settings);
}
});
});
app.put('/profileSettings', (req, res) => {
SettingsModel.findById("5ec40c318f3ebfe68a400e6f", (err, settings) => {
if (err) {
res.status(500).send(err);
}
if (settings) {
settings.main_email = req.body.main_email;
settings.bio_intro = req.body.bio_intro;
settings.bio_tagline = req.body.bio_tagline;
settings.bio_pic = req.body.bio_pic;
settings.bio = req.body.bio;
settings.linkedin_url = req.body.linkedin_url;
settings.gitHub_url = req.body.gitHub_url;
settings.save().then((err, settings) => {
console.log('err: ', err);
console.log('settings: ', settings);
if (err) {
res.status(500).send(err);
//res.json(err);
} else {
res.json(settings);
}
});
} else {
res.status(404).send('Settings Failed to Update');
}
});
});
SO the get works as expected and the put actually updates all the values in the mongo db. But inside the save method the err and settings are both the same. When this code runs it sends a 500 error to the client even though everything worked on the backend.
console.log('err: ', err);
console.log('settings: ', settings);
if (err) {
res.status(500).send(err);
//res.json(err);
} else {
res.json(settings);
}
});
if i put res.json(err)
in the if(err){}
then it returns the same as res.json(settings)
and I get a 200 status but this doesn't let me properly handle errors.
Thanks in advance. Here are the versions I am using
node: 10.15.1
express: 4.16.1
mongoose: 5.9.14
mongoDB Atlas Service