我添加了一个 UpdateCustomer
方法,该方法传入要保存到数据库的修改后的客户。但在更新的文档上调用 ReplaceOneAsync
时,我遇到了错误。
我咨询过以下example和 api reference ,两者都声明传递 ReplaceOneAsync
filter
和 document
参数。
但是由于参数不正确而引发的具体错误如下:
Error 1 The best overloaded method match for 'MongoDB.Driver.IMongoCollection<MongoDBApp.Models.CustomerModel>.ReplaceOneAsync(MongoDB.Driver.FilterDefinition<MongoDBApp.Models.CustomerModel>, MongoDBApp.Models.CustomerModel, MongoDB.Driver.UpdateOptions, System.Threading.CancellationToken)' has some invalid arguments
Error 2 Argument 2: cannot convert from 'MongoDB.Bson.BsonDocument' to 'MongoDBApp.Models.CustomerModel'
有人对理解该错误有任何提示吗?
UpdateCustomer
方法:
public async Task UpdateCustomer(CustomerModel customer)
{
var collection = StartConnection();
var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);
BsonDocument doc = new BsonDocument();
doc["_id"] = customer.Id;
doc["firstName"] = customer.FirstName;
doc["lastName"] = customer.LastName;
doc["email"] = customer.Email;
//error thrown here on the ReplaceOneAsync params..
await collection.ReplaceOneAsync(filter, doc);
}
以及关联的StartConnection方法:
private static IMongoCollection<CustomerModel> StartConnection()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("orders");
//Get a handle on the customers collection:
var collection = database.GetCollection<CustomerModel>("customers");
return collection;
}
最佳答案
您需要一直使用类型化集合,这意味着插入 CustomerModel
的实例,而不是 BsonDocument
:
await collection.ReplaceOneAsync(filter, customer);
或者将无类型文档与 BsonDocument
一起使用,但从一开始就这样做:
var collection = database.GetCollection<BsonDocument>("customers");
您收到这些编译错误是因为您混合了这两个选项。
关于c# - 如何在 MongoDB .Net 中更新插入文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33876799/