[CSHARP-77] MongoCollection.Save() Upserts a random document if it cannot match the ID. Created: 22/Oct/10  Updated: 19/Oct/16  Resolved: 22/Oct/10

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Justin Dearing Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I have a class:

public class Foo
{

public ObjectId _id

{ get; set; }

public string Name { get; set; }

public string Summary

{ get; set; }

}

And I have a function for inserting it

public void EditFoo(Foo fooBar)

{ _db["fooBar"].Save(fooBar, SafeMode.True); }

If fooBar._id exists in the database the save function does an update. If fooBar.Id does not exist it seems as if the driver is picking a document in the collection. and replacing it with my content.



 Comments   
Comment by Robert Stam [ 22/Oct/10 ]

Fixed. Was a complicated combination of not properly detecting which property of the class should be the Id and then not properly handling Save or Insert of a document that has no Id. So there were actually several related bugs. Part of the solution involved adding these new methods to IBsonSerializer:

bool DocumentHasIdProperty(object document);
bool DocumentHasIdValue(object document, out object existingId);
void GenerateDocumentId(object document);

and adding a new IBsonIdGenerator interface with these methods:

object GenerateId();
bool IsEmpty(object id);

The first operate at the document level and handle:

1. Determining whether the document has an Id property
2. Determining whether the Id property has been assigned a value yet
3. Generating and assigning a new Id value to the Id property

The last operate at the level of the Id property value and handle:

1. Determining whether the Id value is empty or not
2. Generating a new value

Finally, the fix involved modifying Insert and Save to use these new methods to correctly handle the various scenarios:

1. The document has no Id property
2. The document has an Id property but it has an empty value
3. The document has an Id proeprty and it already has a non-empty value

Generated at Wed Feb 07 21:35:44 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.