Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert not creating Id?

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?

like image 672
goldfinger Avatar asked Nov 10 '12 17:11

goldfinger


2 Answers

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.

like image 103
Andrew Orsich Avatar answered Oct 22 '22 14:10

Andrew Orsich


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.

like image 26
Juzzbott Avatar answered Oct 22 '22 15:10

Juzzbott