I have created a simple object with getters and setters:
public class MemberCanonical : IMemberCanonical
{
public ObjectId Id { get; set; }
public String username { get; set; }
public String email { get; set; }
public String status { get; set; }
public IEnumerable<string> roles { get; set; }
}
Now I want to insert a new member into the database with:
try
{
memberObj.username = username;
memberObj.email = email;
memberObj.status = "active";
// memberObj.Id = new ObjectId().ToString();
this.membershipcollection.Insert(memberObj, SafeMode.True);
return true;
}
catch(Exception ex)
{
return false;
}
I would expect insert to create a unique _id (Id), but that's not happening. Upon insert when I view the _id field I get "0000000...."
What do I need to do in order for Mongo to generate its own _id on insert?
Just mark your Id property with [BsonId]
attribute, and generated id value will be there!
public class MemberCanonical : IMemberCanonical
{
[BsonId]
public ObjectId Id { get; set; }
this.membershipcollection.Insert(memberObj, SafeMode.True);
var idYouLookingFor = memberObj.Id;
Or alternative way, suggested by @Kobi: "use _id field name instead of Id" should also work.
I use a combination of the [BsonId]
attribute and the constructor to create the Id value.
For example
public class Something {
[BsonId]
public string Id { get; set; }
public Something() {
this.Id = ObjectId.GenerateNewId().ToString();
}
}
This is so that I always have a populated Id field for the object. When the entity is retrieved from the database, the Id field is overwritten with the actual Id value from the database. Win Win.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With