2
I am crud using Node, Express and Mongodb, but I have a problem with the update operation when using the findByIdAndUpdate()
Mongoose it is not updating the document but creating a new.
contactController.js:
module.exports.getEditData = function getEditData(req, res) {
let data = {
id: req.body.id,
name: req.body.name,
surname: req.body.surname,
email: req.body.email,
phone: req.body.phone
}
contactModel.updateContact(data.id, data);
res.redirect("/contacts");
}
contactModel.js:
updateContact(id, data) {
Model.findByIdAndUpdate(id, {
name: data.name,
surname: data.surname,
email: data.email,
phone: data.phone
}, {new: true})
.then(e => console.log(e));
}
Schema:
const ContactSchema = new mongoose.Schema({
name: {type: String, required: true},
surname: {type: String, require: true},
email: {type: String, require: true},
phone: {type: String, require: false}
});
Your code seems to be correct. You have tried testing with
findOneAndUpdate
?– Cmte Cardeal
This behavior of inserting a new document is due to the fact that 1 - Do not find the document id and 2 - has the parameter
upsert
astrue
, which, by its code, is not your case.– Cmte Cardeal
Hello, I never used this option
{new: true}
. I could try without it, or even put {new: false. Fiz uma pesquisa na documentação do Mongoose, e não achei esse uso. Uma segunda opção, que uso muito, é
Model.findById`, updates and saves!– Jorge Guerra Pires
vc is forgetting to put $set Model.findByIdAndUpdate(id, { $set: { name: 'Jason Bourne' }}, options, callback)
– jcardoso