简体   繁体   中英

mongodb C# driver not generating ObjectId of newly added document in embedded list of objects when using Update.Push

I am using mongodb C# driver and trying to add "Goal" Entity in the "List", contained in Client class, but mongodb always returns an empty objectId og Goal.

Client.cs

    public class Client
    {
    public string UserName { get; set; }

    [BsonId]
    public ObjectId ClientId { get; set; }

    [BsonIgnore]
    public string ClientIdString
    {
        get
        {
            return this.ClientId.ToString();
        }
    }

    [BsonRequired]
    public string ClientName { get; set; }

    public string EmailAddress { get; set; }

    public string CompanyName { get; set; }

    public List<Goal> Goals { get; set; }
    }

Goal.cs

public class Goal
{

    public ObjectId GoalId { get; set; }

    [BsonRequired]
    public string Title { get; set; }

    public string Description { get; set; }

    [BsonDefaultValue(State.NotStarted)]
    public State GoalState { get; set; }

    [BsonIgnore]
    public string StateString 
    {
        get
        {
            return this.GoalState.ToString();
        }
    }

}

and i am trying to add Goal to client with following code:

IMongoQuery query = Query<Client>.EQ(eq => eq.ClientId, id);
                IMongoUpdate update = Update<Client>.Push<Goal>(push => push.Goals, goal);

                WriteConcernResult result = this.ClientCollection.Update(query, update);

But every time mongodb returns an empty objectId of newly added Goal in the List in client.

Kindly guide me what i am doing wrong?

Thanks in advance. :)

Kindly guide me what i am doing wrong?

Nothing really, but you're expecting the wrong behavior.

Embedded documents don't have an _id . Of course, you can force mongodb to create a field that happens to have that name, but unlike the root _id , such a field has no special semantics and there's no default index. The lack of these special semantics is also the reason why the driver doesn't bother generating a value for the field for you.

Generally speaking, having a unique index in an embedded document is often a sign of a malformed data structure. Make sure such an id is strictly required. If the id must be globally unique, it appears the embedded document might also make sense or be relevant if it had another parent, which indicates that it should be a first-level citizen, ie have a collection of its own.

Remember that this also a question of ownership - what happens with concurrent writes? Of course, you can go to great lengths and only use atomic modifiers to allow different writes to one document, but that is unnecessarily complicated IMHO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM