首页 > 解决方案 > 覆盖与特定 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;
}

但显然这是不正确的。任何反馈将不胜感激。

标签: mongodbasp.net-coreurl-shortener

解决方案


我发现在帮助我解决这个问题方面绝对没有任何用处,但我最终得到了这个工作:

控制器类:

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;

推荐阅读