Итак, я пытаюсь обновить существующие записи в MongoDB, и обновление записей отображается правильно, но в консоли я все еще вижу эти предупреждения и ошибки:
{"name":"Bruce","number":"22222","date":"2020-12-18T20:08:45.446Z","id":"5fdd0c4d72a07e5d0c63c056"}
**** { _id: 5fdd0c4d72a07e5d0c63c056,
name: 'Bruce',
number: '22222',
date: 2020-12-19T06:29:29.022Z,
__v: 0 }
// ^------- this is the record body sent from the frontend and it's being updated correctly.
// but I still get this following errors:
error: Error [ERR_HTTP_HEADERS_SENT]
PUT /api/persons/5fdd0c4d72a07e5d0c63c056 402 99 - 116.533 ms {"name":"Bruce","number":"22222","date":"2020-12-18T20:08:45.446Z","id":"5fdd0c4d72a07e5d0c63c056"}
(node:8288) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]:
Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (E:\fsopen_revision\phonebook\server\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (E:\fsopen_revision\phonebook\server\node_modules\express\lib\response.js:170:12)
at Contact.findByIdAndUpdate.then.catch (E:\fsopen_revision\phonebook\server\index.js:136:11)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:8288) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a
catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
Код используется для выполнения обновления:
app.put("/api/persons/:id", (req, res) => {
console.info(JSON.stringify(req.body));
const id = Object(req.params.id);
const body = req.body;
const newPerson = {
name: body.name,
number: body.number,
date: new Date(),
};
Contact.findByIdAndUpdate(id, newPerson, {
new: true,
})
.then((updatedContact) => {
console.info("**** ", updatedContact);
return res.json(updatedContact).send({ message: "Updated" });
})
.catch((e) => {
console.info("error: ", e.name);
res.send(402).json({ name: e.name });
});
});
Фронтенд работает нормально и данные тоже корректно обновляются:



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Попробуйте этот синтаксис, сначала проверьте, существует ли идентификатор пользователя в БД, затем findByIdAndUpdate с обработкой ошибок и ответов:
updateUser: (req, res) => {
const id = Object(req.params.id);
const body = req.body;
const newPerson = {
name: body.name,
number: body.number,
date: new Date(),
};
Contact.findById(id, (err, res) => {
if (err) return res.status(500).send({message: 'Error finding user'});
});
User.findByIdAndUpdate(id, newPerson, {new: true}, (err, updatedContact) => {
if (err) return res.status(500).send({message: 'Error updating'});
if (!userUpdated) return res.status(404).send({message: 'user doesnt exists'});
return res.status(200).send(contact: updatedContact);
});
}Ваше сообщение об ошибке гласит: Cannot set headers after they are sent to the client
Вы не можете отправить ответ два раза. Либо используйте метод json(), либо метод send(). Каждый из них создает заголовки для ответа, отправляет тело (полезную нагрузку) и затем завершает отправку ответа с сервера.
// incorrect use of express api
res.json(updatedContact).send({ message: "Updated" });
// change to
res.json({ message: "Updated", contact: updatedContact });