0
votes

I have an object that has a parent class that may or may not set a _id field.

In this case, the _id field is not set and I pass an object through to

collection.insertOne(object)

Normally mongo generates a ObjectId() for a _id that isn't specified, but for some reason whenever _id is specified by a parent class and is not set, it is generating an id, bug is saving the id as a string in the database rather than an ObjectId.

What I'm passing through

{ "name" : "name" }

Expected:

{ "_id" : ObjectId("5cb89a7cf5e722a3d493ce8b"), "name" : "name" }

Actual:

{ "_id" : "5cb89a7cf5e722a3d493ce8b", "name" : "name" }

What I think is happening is that it sees that the parent class has a _id field, but can't find it, causing somthing like this to be passed through.

{ "_id" : null, "name" : "name" }

and as a result mongo doesn't generate an ObjectId but a string.

Is this a bug?

Thanks in advance!

1
Have you tried to declare the _id as ObjectId ? ā€“ Davide Lorenzo MARINO
There are other classes that require this to not always be an object id but as a string. ā€“ Andy
I'm trying to upgrade to mongo 4 and it is giving me this issue. Our previous version of mongo saved it as an objectId. (Mongo v3.4.14) ā€“ Andy

1 Answers

0
votes

I think this is the normal behavior of mongoDB. I only use mongo with javascript and this is the behavior it always shows. Iā€˜m wondering if this actually makes any difference for your usecase, as the id is still unique