goldfinger
goldfinger

Reputation: 1115

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?

Upvotes: 8

Views: 6881

Answers (3)

Juzzbott
Juzzbott

Reputation: 1769

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.

Upvotes: 4

Kiranmai Harshi
Kiranmai Harshi

Reputation: 1

Use [BsonId] on whichever unique property you want to use. You can even ignore the ObjectID type and create your own.

For example:

[BsonId]
public string studentid{get; set;}

Upvotes: -1

Andrew Orsich
Andrew Orsich

Reputation: 53675

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.

Upvotes: 11

Related Questions