Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB id remains null after InsertOneAsync

I have a base class Entity that has a string Id member and a derived class A.

But when creating a new instance of the derived class and using InsertOneAsync to add it to my collection, the document is added to the database with null as the Id value.

Using an ObjectId as the Id does seem to work, but I'm trying to prevent MongoDB dependency in my models.

I also experimented with the following code, but the results are the same:

BsonClassMap.RegisterClassMap<Entity>(cm =>
{
    cm.MapIdField(x => x.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
});
like image 603
Randy Voet Avatar asked Apr 22 '15 13:04

Randy Voet


People also ask

Are MongoDB IDS sequential?

Although MongoDB does not support auto-increment sequence as a default feature like some relational databases, we can still achieve this functionality using a counter collection. The counter collection will have a single document that tracks the current unique identifier value.

Can I use ID in MongoDB?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record.

Does MongoDB store null value?

Indeed, it's not possible to store null values in a MongoDB document using a DataFrame. The Python None values are considered as missing attributes accordingly to this NoSQL specific allowance. However, if your column is numerical, you can force writing a null value by setting it to NaN.

Is ID mandatory in MongoDB?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.


1 Answers

I had the same issue and finally got it to work (with the 2.0 driver) with these attributes:

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonIgnoreIfDefault]

Or the equivalent BsonClassMap fluent interface:

BsonClassMap.RegisterClassMap<Entity>(cm =>
{
      cm.MapIdField(x => x.Id)
      .SetSerializer(new StringSerializer(BsonType.ObjectId))
      .SetIgnoreIfDefault(true);
});

I tried to get the same working with .ReplaceOneAsync with Upsert on but that always leaves the id still null

like image 58
Mike Cowgill Avatar answered Sep 19 '22 15:09

Mike Cowgill