mongodb - 覆盖与特定 ObjectId 关联的数据?
问题描述
我正在尝试更改已经创建并存储在数据库中的随机 ObjectId 下的“OriginalUrl”,如下所示:
{
"_id" : ObjectId("5b1551d571231d26444d5c35"),
"Title" : "Test5",
"Code" : "n3b4nb_jxnm2",
"OriginalUrl" : "https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api-mac?view=aspnetcore-2.1",
"Url" : null
}
我有一个 Post Get 和 Delete 方法工作,但我的 Put 方法没有按照我理解的方式执行此操作,根据https://docs.microsoft.com/
[HttpPut("{id}")]
public async Task<IActionResult> Update(string id, [FromBody] string su)
{
var gameFromDb = await _repo.GetAsync(id);
if (gameFromDb == null)
{
return new NotFoundResult();
}
su = gameFromDb;
// await _repo.Update(su);
return new OkObjectResult(su);
}
我仍在学习,因此如果这是我尚未在本网站或其他地方发现的明显答案,我深表歉意。
更新:
[HttpPut("{id}")]
public async Task<IActionResult> Update(string id, [FromBody] string su)
{
return (await _repo.Update(ObjectId.Parse(id)))
? (IActionResult)Ok("Updated Successfully")
: NotFound();
}
}
}
存储库:
public async Task<bool> Update(ObjectId id)
{
var filter = new ShortUrl("_id", 10);
var replacement = new BsonDocument { { "_id", 10 }, { "x", 2 } };
var r = _db.Urls.ReplaceOne(filter, replacement);
return r.IsAcknowledged
}
更新:
我意识到有类似的文章,例如:
https://stackoverflow.com/questions/41493327
和:
https://stackoverflow.com/questions/41483648
但两者都没有帮助。我不想将“First Name”、“John”硬编码为“FirstName”、“Jack”。我需要能够搜索与“John”关联的 Id,并将 First Name 更改为用户传递的任何内容。我在想这样的事情:
public async Task<bool> Update(ObjectId id)
{
var filter = Builders<ShortUrl>.Filter.Eq(x => x.Id, id);
var r = await _db.UrlsFindOneAndUpdate(filter, update);
return r.IsAcknowledged;
}
但显然这是不正确的。任何反馈将不胜感激。
解决方案
我发现在帮助我解决这个问题方面绝对没有任何用处,但我最终得到了这个工作:
控制器类:
public async Task<IActionResult> Update(string id, [FromBody]ShortUrl entity)
{
if (await _repo.Update(id, entity))
{
return Ok();
}
return NotFound();
}
}
存储库类:
public async Task<bool> Update(string Id, ShortUrl shortUrl)
{
var objId = ObjectId.Parse(Id);
var ub = Builders<ShortUrl>.Update;
var updates = new List<UpdateDefinition<ShortUrl>>();
if (!string.IsNullOrWhiteSpace(shortUrl.Title))
{
updates.Add(
ub.Set(x => x.Title, shortUrl.Title));
}
if (!string.IsNullOrWhiteSpace(shortUrl.OriginalUrl))
{
updates.Add(
ub.Set(x=>x.OriginalUrl,shortUrl.OriginalUrl));
}
if (updates.Count == 0) return false;
var result = await _db.Urls.UpdateOneAsync(
x => x.Id == objId,
ub.Combine(updates));
return result.ModifiedCount > 0;
推荐阅读
- export-to-excel - 无法导出包含图表的页面
- reactjs - MongoDb $addToSet 数组在提交两次后更新
- java - 选择求和条件连接表mysql
- spring-mvc - 使用 Spring Web Flow 上传文件
- vb.net - 使用子字符串在字符串中拆分日期和时间
- ubuntu - 在 Ubuntu 上阻止 ASN 而不是 IP/CIDR
- jquery - 使用 .html() 未显示图标
- php - 如何使用 PHP 从 JSON 中获取最后 5 个数据?
- python - 如何从值为“No”而不是 NaN 的列中清除值?
- matlab - 在 Win10 上为 MATLAB 编译 SPAMS 工具箱时出现“未声明的 '_finite'”错误