LiteDB: Invalid BSON data type 'Null' on field '_id'
I agree with @mbdavid's answer. However, when it's for a type you don't own, like something you're using from a 3rd-party assembly, you'll like need to use the BsonMapper:
BsonMapper.Global.Entity<IdentityServer4.Models.IdentityResources.OpenId>()
.Id(oid => oid.Name);
Put this somewhere in your startup code.
For others who might have this problem, here is an example that worked for me.
I have a product class with a field columnId and I added another Id with type objectId
to get rid of that Invalid BSON data type 'Null' on field '_id'
error.
public class Product
{
[BsonId]
public ObjectId Id { get; set; }
public int ColumnId { get; }
public int Quantity { get; private set; }
.....
}
My update method, created in another class is:
public void UpdateQuantity(Product product)
{
var collection = database.GetCollection<Product>("products");
var databaseProduct = collection.FindOne(x =>x.ColumnId.Equals(product.ColumnId));
databaseProduct.DecrementQuantity();
collection.Update(databaseProduct);
}
Type Guid
did not work for me.
When you have a object without an identification, LiteDB convert your object to BsonDocument and create a new "_id" on insert. If you query your database (using shell) you can see your document there with an _id (ObjectId).
But, to update your document, you must use this _id generated on insert (see here: https://github.com/mbdavid/LiteDB/blob/v2.0.0-rc/LiteDB/Core/Collections/Update.cs#L25). Documents without id is useful only when you store this _id in another database (sql) or for insert only.
In you example, if server
is you document id, use [BsonId]
attribute to solve or create an public Guid Id { get; set; }