0

I am trying to make an put request to change some information. I get the new informations from request body, however I want some parameters optional

example: old record --> {name: ugur, surname:k}

put request comes like this--> {name: uur}

so i want surname to stay same but it will be null now which i dont want to.

here is the code snippet :

await User.findOneAndUpdate({filter}, {$set:{name:req.body.name, surname:req.body.surname}})

In this way when user dont send a surname, users surname will be updated as null. Is there a way to get users old surname? for instance -->

await User.findOneAndUpdate({filter}, {$set:{name:req.body.name, surname:req.body.surname || this.getsurname}})

I want to solve it without using if else or first findOne then update the user.

Ugur Kellecioglu
  • 370
  • 1
  • 3
  • 9

1 Answers1

0

Just don't include fields in update, if they are not provided (undefined or null):

const update = {
  ...name && { name },
  ...surname && { surname },
}

await User.findOneAndUpdate({filter}, {$set: update})

&& operator returns right part of expression if first part of expression is truthy, ... is a distructure operator, so basically ...name && { name } means if name exists, add distructure { name } into base object, to make things more clear, imagine we need to add property name equal to request.body.name to the object only if request.body.name exists: { ...request.body.name && { name: request.body.name } }

Nikita Mazur
  • 1,602
  • 1
  • 5
  • 14
  • I didn't understand what ...name && { name } does? can you explain more please? `const update = {...request.body.name && { name },...request.body.surname && { surname},} ` gives me error – Ugur Kellecioglu Jul 14 '21 at 12:32
  • [Filter](https://stackoverflow.com/a/38340730/13587169) i solved the problem filtering the ` object`, but if you can give me some topics i am willing to learn your way too. – Ugur Kellecioglu Jul 14 '21 at 12:58
  • `&&` operator returns right part of expression if first part of expression is truthy, `...` is a distructure operator, so basically `...name && { name }` means if name exists, add distructure `{ name }` into base object, to make things more clear, imagine we need to add property `name` equal to `prop.name` to the object only if `prop.name` exists: `{ ...prop.name && { name: prop.name } }` – Nikita Mazur Jul 14 '21 at 13:13