1

I am updating a document in projects collection. which looks like below:

projects collection

"_id" : ObjectId("5c2df5ccfb98b328c470597b"),
"clientName" : "abc",
"attachments" : [],
"status" : "ongoing",
"assignId" : ObjectId("5c2df3c3fb98b328c4705979"),
"upworkId" : ObjectId("5c2df956b84e902678f416fa")

Now, I am getting upworkId field null or empty from client side, But getting the new value for clientName, status and attachments. So i want to remove the upworkId field and update the other field values in project collection. How can i?

My current update query is:

Project.findByIdAndUpdate(req.params.id, req.body)
  .then((project) => {
    if (!project)
      res.status(400).json({message: MESSAGE.PROJECT_NOT_FOUND});
    else 
      res.status(302).json({message: MESSAGE.PROJECT_UPDATED_SUCCESS});
})

Note: I need to remove the field from the collection for the particular document, I don't want to remove the field from the object.

Rajat
  • 486
  • 1
  • 10
  • 35
  • do you want to update only filled fields? – Artem Ilchenko Jan 03 '19 at 12:59
  • Yes, But i also want to remove the "upworkId" field for particular project, If it didn't exists in req.body. – Rajat Jan 03 '19 at 13:00
  • in this case your code must works fine – Artem Ilchenko Jan 03 '19 at 13:01
  • Possible duplicate of [Remove blank attributes from an Object in Javascript](https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript) – Artem Ilchenko Jan 03 '19 at 13:02
  • @ArtemIlchenko, Please read my question first. I want to remove the field from database, not from the object as i am not sending it from frontend. So why i need it to remove from object? – Rajat Jan 03 '19 at 13:06
  • you write your object into database, aren't you? – Artem Ilchenko Jan 03 '19 at 13:07
  • If you want to set it as null then pass `null` from the frontend itself – Ashh Jan 03 '19 at 16:07
  • @AnthonyWinzlet, Why are you not understanding. I want to remove upworkId field completly for that document. So why i put it's value to null. – Rajat Jan 03 '19 at 16:08
  • 1
    then use `$unset`. `Project.findByIdAndUpdate(req.params.id, { $set: req.body, $unset: { upworkId: '' } })` – Ashh Jan 03 '19 at 16:10
  • 1
    Your question is unclear: the `upworkId` field can be null, or empty. Does that mean an empty string? Does that mean undefined? Does that mean it's not set? Those are three different things. And like @AnthonyWinzlet has already said, use `$unset`. – robertklep Jan 03 '19 at 17:21

1 Answers1

0
Project.findByIdAndUpdate(req.params.id, req.body)
  .then((project) => {
    if (project.length<0)
     then use $unset. Project.findByIdAndUpdate(req.params.id, { $set: req.body, $unset: { upworkId: '' } })
      console.log(result)
    else
 res.send('update sucessfully ')
      })