0

I am new in MongoDB and using version 3.0.11. I have created a field shared_group which is an ObjectId and sometimes this ID could be null.

shared_group:{
            type: Schema.Types.ObjectId,ref:"Group",require:false
},

and in API request I am sending

{
   "data":{
      "shared_group":"null"
    }
}

Error - CastError: Cast to ObjectId failed for value "" at path "shared_group"

if I send shared_group:[ID] then it works fine.

Any suggestion is highly appreciated. Thanks in advance.

Prithviraj Mitra
  • 11,002
  • 13
  • 58
  • 99
  • 1
    Means what it says. The string `"null"` cannot be cast as an `ObjectId`. If you mean to omit it, then you either actually omit it from the request being sent or you remove the invalid value before attempting to create the new object against a schema that wants an `ObjectId` – Neil Lunn Apr 17 '19 at 10:01
  • I also tried removing from the request if blank but I get `Cast to ObjectId failed for value "" at path "shared_group"` – Prithviraj Mitra Apr 17 '19 at 10:08
  • 1
    I did not say **blank** ( which is obviously where the `""` comes from even though you should `"null"` in the question ), but actually **remove it**, so remove the `shared_group` key from any input if it does not contain a valid `ObjectId` value. `delete obj.data.shared_group` would be the JavaScript way to remove that key from the document, where the variable containing was named `obj` in that case. – Neil Lunn Apr 17 '19 at 10:14
  • Bit weird but it all seems working fine now. Thank you. – Prithviraj Mitra Apr 17 '19 at 10:52

0 Answers0