c# - 我怎么知道 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 为真时,是否存在可能发生故障的情况?
解决方案
推荐阅读
- python - 更改 ms 团队聊天中的消息
- c# - 值之间范围内的伪造字符串长度
- python - 将我的 .db 文件数据发送到电子邮件并删除其中的旧记录
- reactjs - 没有导航道具的反应本机导航
- django - 页面未形成 404 错误 - 未显示 (找到) 的蛞蝓 ID:http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily
- flutter - Flutter With VSCODE :Exception: Gradle task assembleDebug failed with exit code 1 BUILD FAILED in 22s
- gitlab - 如何通过 LDAP 使用 python 登录 GitLab?(使用版本 ce-8.1.4)
- javascript - 使用特定列从数组填充 DataTable
- flutter - 使用不包含 Navigator Flutter 异常的上下文请求的 Navigator 操作
- reactjs - Mapbox 地图在 useEffect 返回数据之前被加载