首页 > 解决方案 > 我怎么知道 UpdateOneAsync 失败(来自 UpdateResult)?

问题描述

我正在尝试将一个文档插入 MongoDb。非常简单,但是我要检查什么(除了存在异常)才能知道它失败了?

代码:

public async Task<UpdateResult> UpdateDocument<T>(
    string sConnectionString, 
    string sDatabaseName, 
    string sCollectionName, 
    Expression<Func<T, bool>> filter, 
    UpdateDefinition<T> update,
    bool bUpsert,
    System.Threading.CancellationToken cancellationToken
    )
{
    ConnectToDb(sConnectionString);

    IMongoDatabase db = _mongoClient.GetDatabase(sDatabaseName);

    IMongoCollection<T> collection = db.GetCollection<T>(sCollectionName);

    return await collection.UpdateOneAsync<T>(filter, update, new UpdateOptions() { IsUpsert = bUpsert }, cancellationToken);
}

private void ConnectToDb(
    string sConnectionString
    )
{
    if(sConnectionString != _sConnectionString)
    {
        _mongoClient = null;
        _mongoClient = new MongoClient(sConnectionString);

        _sConnectionString = sConnectionString;
    }
}

然后是调用它的代码:

try
{
    MongoDB.Driver.UpdateResult updateResult = await _db.UpdateDocument<Models.NodeBoardModel>(
        _dbSettings._sURLMongoDbConnectionString,
        _dbSettings._sDatabasename, Constants.NodeBoardCollectionName,
        node => node.Id == boardToServerData._request.Id,
        MongoDB.Driver.Builders<Models.NodeBoardModel>.Update.Set(node => node.RemoteBoard, dbboardmodel),
        true,
        stoppingToken
        );

    bool bAcked = updateResult.IsAcknowledged;
    if(updateResult.
}
catch(AggregateException aggEx)
{
    Models.Errors errors = null;

    errors = Helpers.ProcessAggregateException(
        aggEx, 
        Models.eError.UPSERTREMOTEBOARD
        );

    _logger.LogError(errors.GetErrorModel()._sSpecificErrorMessage);
}
catch(Exception ex)
{
    Models.Errors errors = null;

    errors = Helpers.ProcessException(
        ex, 
        Models.eError.UPSERTREMOTEBOARD
        );

    _logger.LogError(errors.GetErrorModel()._sSpecificErrorMessage);
}

在我看到 UpdateResult 之前,它看起来很简单(只需查找异常)。没有太多关于如何处理它的上下文:

http://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_UpdateResult.htm

所以即使我没有得到异常,它仍然会失败吗?我猜如果 IsAcknowledged 是假的,那么我就失败了。当 IsAcknowledged 为真时,是否存在可能发生故障的情况?

标签: c#mongodb

解决方案


推荐阅读