findByIdAndUpdate() is creating document instead of updating

Asked

Viewed 62 times

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?

  • 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 as true, which, by its code, is not your case.

  • 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!

  • vc is forgetting to put $set Model.findByIdAndUpdate(id, { $set: { name: 'Jason Bourne' }}, options, callback)

1 answer

0

I even did a test here. was normal. could be the id if it is not in the schema it does not consider. I used _id

var mongoose = require('mongoose');
const { Types } = mongoose;
// "mongoose": "^6.0.3",
let db = mongoose.connect('mongodb://teste:123456@localhost:27017/teste', {
  maxPoolSize: 50,
  wtimeoutMS: 2500,
  useNewUrlParser: true
});
db = mongoose.connection;
db.once('open', () => {
  console.log('Connection Success.. !');
  return db
});
db.on('error', console.error.bind(console, 'connection error:'));

var userSchema = new mongoose.Schema({
  name: {type: String, required: true},
  surname: {type: String, require: true},
  email: {type: String, require: true},
  phone: {type: String, require: false}
});

let User = db.model('user', userSchema)

let objnew = {
  
  name:'musta',
  surname: 'fa',
  email: '[email protected]',
  phone: ''
}
let objupdate = {
  name:'terror',
  surname: 'mustafa',
  email: '[email protected]',
  phone: ''
}
async function run() {
  User.findByIdAndUpdate({ _id: Types.ObjectId("612d953d4c86161be1515630") }, objnew, { new: true }).then(e => console.log(e));

  let a = await User.findByIdAndUpdate({ _id: Types.ObjectId("612d953d4c86161be1515630") }, { $set: objupdate }, { new: true }).exec();
  console.log('A', a);
}

run()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.