how can i find one record with the filter _id and update that record using the nodejs and mongodb,mongoose how can i find one record with the filter _id and update that record using the nodejs and mongodb,mongoose mongoose mongoose

how can i find one record with the filter _id and update that record using the nodejs and mongodb,mongoose


Issue with your code is you're trying to club two different functionalities given in Mongoose .save() which works on mongoose model's instances i.e; documents & .findOneAndUpdate() which works directly on mongoose models.

So if you've all the filters & changes you would directly use .findOneAndUpdate() function on mongoose model to update an existing document :

let student = {  _id: mongoose.Types.ObjectId(_eId),  name: name,  studentId: id,  status: status,};updateToDb(student);/** passing in .Js Object as input */function updateToDb(studentInput) {  console.log(studentInput._id + " studentId");  var studentId = studentInput._id;  var filter = { _id: studentId };  delete studentInput._id; // Deleting `_id` from studentInput as it shouldn't be there in update object  Student.findOneAndUpdate(filter, studentInput, (err, student) => {    if (!err) {      console.log("insertion to db sucess");    } else {      console.log("insertion failed " + err);    }  });}

So with .findOneAndUpdate() we'll pass { multi : true } option to insert a new document if no document has matched with filter part. But with .save() we can actually use it for new insert & updates as well, If _id exists in input request & a document in DB matches with it then .save() will be considered as update operation otherwise it will treated as insert operation, But it doesn't work on mongoose models it will only work on instances of mongoose models.

/** Here since you're passing in instance of mongoose model then use .save() */var student = new Student();student._id = mongoose.Types.ObjectId(_eId);student.name = name;student.studentId = id;student.status = status;updateToDb(student);function updateToDb(student) {  console.log(student._id + "      studentId");  student.save((err, student) => {    if (!err) {      console.log("insertion to db sucess");    } else {      console.log("insertion failed " + err);    }  });

Ideally .save() is used on updates when you first read a document from DB & then make necessary changes, as mongoose tracks changes occurring to document at the end all you need to do is to apply .save() on that doc.