如何在MongoDB .Net中增补文档?

问题描述 投票:1回答:2

我正在添加UpdateCustomer方法,该方法将经过修改的客户传递给数据库,以将其持久化。但是在更新文档上调用ReplaceOneAsync时遇到错误。

我已经咨询了以下exampleapi reference,它们都声明要传递ReplaceOneAsyncfilterdocument参数。

但是由于不正确的参数而引发特定错误,如下所述:

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;
}
c# .net mongodb-.net-driver mongodb-csharp-2.0
2个回答
1
投票

您需要一直使用类型化集合,这意味着要插入CustomerModel而不是BsonDocument的实例:

await collection.ReplaceOneAsync(filter, customer);

或将无类型的字符与BsonDocument一起使用,但从一开始就这样做:

var collection = database.GetCollection<BsonDocument>("customers");

由于混用了这两个选项,因此出现了这些编译错误。


0
投票

这对我有用

var filter = Builders.Filter.Where(x => x.Id == customer.Id); await Collection.ReplaceOneAsync(filter, item, new ReplaceOptions { IsUpsert = true });

© www.soinside.com 2019 - 2024. All rights reserved.