Home > other >  Need to pass ObjectId with a null value to store in mongodb
Need to pass ObjectId with a null value to store in mongodb

Time:01-25

i have a restful api where i am passing String, ObjectId and integer in the request body from postman. I have an objectId for another collection school.

The dom file is

public class test {
   private String id;
   private String name;
   private int age;
   private String address;
   private ObjectId school;
   //getters and setters

}

In postman the POST body request is

{"name":"tester",
 "age":17,
 "address":"test address",
  "school":"507f1f77bcf86cd799439011"}

While passing the value for ObjectId as null, im getting error,

{"name":"tester",
 "age":17,
 "address":"test address",
 "school":""}

but this error doesnt occur if i omit the field entirely in the request body. i.e

{"name":"tester",
 "age":17,
 "address":"test address"
}

How can i pass a null value to school field without getting a error?

CodePudding user response:

Mongo expects a ObjectId as the only possible value for 'school'. It will not take 'null' in its place. I would use an absence of the school value to mean null in your application code.

This post may also help answer your question if the above doesn't get your where you want.

how to set mongo objectId field to null or empty or even delete the field?

  •  Tags:  
  • Related