I've added a method to a MongoDB database repository class, that is supposed to upsert/update documents.
But I noticed after calling the UpdateCustomer()
on a document, a new one is created and the old is unmodified. In short, the upsert method is behaving like a save new method.
In order to debug the issue I checked the filter being used, which seems to be correct:
var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);
But when I step into the result, it shows a MatchedCount and ModifiedCount of zero. Indicating that filter doesn't match the existing document.
I also checked that the ID's of both the original and modified documents are the same, which they are:
Does anyone know why the document isn't being updated in this instance?
The complete UpdateCustomer method is as follows, the customer object is the SelectedCustomer from my VM which has been modified.:
public async Task UpdateCustomer(CustomerModel customer)
{
var collection = StartConnection();
var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);
var result = await collection.ReplaceOneAsync(filter, customer, new UpdateOptions { IsUpsert = true });
}
My documents are defined as follows on my remote DB (last two records showing the same ID number):
And when I call a toString() on my filter, the following query is created:
find({ \"_id\" : ObjectId(\"5565d8adba02d54a4a78be93\") })
This is the CustomerModel class as reuqested:
namespace MongoDBApp.Models
{
public class CustomerModel : INotifyPropertyChanged
{
private ObjectId id;
private string firstName;
private string lastName;
private string email;
/// <summary>
/// This attribute is used to map the Id property to the ObjectId in the collection
/// </summary>
[BsonId]
public ObjectId Id
{
get
{
return id;
}
set
{
id = value;
}
}
[BsonElement("firstName")]
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
RaisePropertyChanged("FirstName");
}
}
[BsonElement("lastName")]
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
RaisePropertyChanged("LastName");
}
}
[BsonElement("email")]
public string Email
{
get
{
return email;
}
set
{
email = value;
RaisePropertyChanged("Email");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}