gpt4 book ai didi

mongodb - 构造函数 MongoDB.Bson.ObjectId() 在 .NET Core 2 中不起作用

转载 作者:可可西里 更新时间:2023-11-01 10:46:49 25 4
gpt4 key购买 nike

我有第一个项目试图使用 MongoDB.Driver 从 mongodb 获取值。我可以连接到数据库和“GetAll”,但是当发出需要 ObjectId 的请求时,我收到该异常:

Exception has occurred: CLR/System.IndexOutOfRangeException
An exception of type 'System.IndexOutOfRangeException' occurred in MongoDB.Bson.dll but was not handled in user code: 'Index was outside the bounds of the array.'

更具体:

at MongoDB.Bson.ObjectId.FromByteArray(Byte[] bytes, Int32 offset, Int32& a, Int32& b, Int32& c)
at MongoDB.Bson.ObjectId..ctor(String value)
at TodoApi.Controllers.TodoController.GetById(String id) ...

方法 GetById:

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
var objId = new ObjectId(id); << this line exceptions occures
var item = objds.GetTodoItem(objId);

if (item == null) { return NotFound(); }

return new ObjectResult(item);
}

DataAccess 中的方法 GetTodoItem:

public TodoItem GetTodoItem(ObjectId id)
{
var res = Query<TodoItem>.EQ(p=>p.Id,id);
return _db.GetCollection<TodoItem>("TodoApi").FindOne(res);
}

.csproj

  <ItemGroup>
<PackageReference Include="MongoDB.Driver" Version="2.5.0" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="MongoDB.Driver.Core" Version="2.5.0" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="MongoDB.Bson" Version="2.5.0" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="mongocsharpdriver" Version="2.5.0" />
</ItemGroup>

最佳答案

您可以像这样生成一个新的 ObjectId:

ObjectId.GenerateNewId();

但很可能您不会在数据库中找到任何具有该 ID 的文档。通常,当您想要执行插入并且不希望 Mongo 为新插入的文档分配随机 ID(假设您想要将该 ID 返回给用户)时,您会生成一个 ObjectId。

现在,假设您要查找具有 id = 5a71ae10a41e1656a4a50902 的特定文档,您可以执行以下操作:

var id = "5a71ae10a41e1656a4a50902";
var context = new YourContext();
var builder = Builders<TodoItem>.Filter;
var filter = builder.Eq(x => x.Id, ObjectId.Parse(id));
var result = await context.TodoItemCollection.FindAsync(filter);

关于mongodb - 构造函数 MongoDB.Bson.ObjectId() 在 .NET Core 2 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49849054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com