Reputation: 23
This is my createUpdate function
const createUpdateProfile = (req, res) => {
//Fillout Schema
let uuid = req.user.identities[0].id;
let provider = req.user.identities[0].provider;
let email = req.user.email;
let firstName = req.user.name.split(' ').slice(0, -1).join(' ');
let lastName = req.user.name.split(' ').slice(-1).join(' ');
let pictureUrl = req.user.picture;
let profileToSafe = new Profile({
uuid: uuid,
provider: provider,
email: email,
firstName: firstName,
lastName: lastName,
pictureUrl: pictureUrl
});
let profileToUpdate = new Profile({
email: email,
firstName: firstName,
lastName: lastName,
pictureUrl: pictureUrl
});
//createUpdate
Profile.findOne({ uuid }).then(object => {
if (object !== null) {
Profile.findByIdAndUpdate(object._id, profileToUpdate, function (err, raw) {
if (err) {
console.log('callback -> err', err);
}
console.log('callback -> raw', raw);
res.status(200).send('successful operation update');
});
} else {
profileToSafe.save();
res.status(200).send('successful operation create');
}
})
}
Everything works, despite updating an existing record.
So the problem is in this code area:
Profile.findByIdAndUpdate(object._id, profileToUpdate, function (err, raw) {
if (err) {
console.log('callback -> err', err);
}
console.log('callback -> raw', raw);
res.status(200).send('successful operation update');
});
I have no idea why, but it is trying to override the _id field, even if it is not defined in the profileToUpdate schema.
Upvotes: 0
Views: 578
Reputation: 23
Got it work, after reading this.
The trick is to remove the id manually, before trying to update.
Profile.findOne({ uuid }).then(object => {
if (object !== null) {
var upsertData = profileToUpdate.toObject();
delete upsertData._id;
Profile.update({ uuid }, upsertData, { upsert: true }, function (err, raw) {
if (err) {
console.log('callback -> err', err);
}
console.log('callback -> raw', raw);
res.status(200).send('successful operation update');
});
} else {
profileToSafe.save();
res.status(200).send('successful operation create');
}
})
Upvotes: 1