构造函数MongoDB.Bson.ObjectId()在.NET Core 2中不起作用
我有一个项目试图使用mongodb.Driver从mongodb获取一个值。我可以连接到数据库和“GetAll”,但当请求需要ObjectId的人时,我会收到该异常:构造函数MongoDB.Bson.ObjectId()在.NET Core 2中不起作用,mongodb,.net-core,mongodb-.net-driver,objectid,Mongodb,.net Core,Mongodb .net Driver,Objectid,我有一个项目试图使用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
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);
}
public TodoItem GetTodoItem(ObjectId id)
{
var res = Query<TodoItem>.EQ(p=>p.Id,id);
return _db.GetCollection<TodoItem>("TodoApi").FindOne(res);
}
[HttpGet(“{id}”,Name=“GetTodo”)]
公共IActionResult GetById(字符串id)
{
var objId=新对象id(id);p.id,id);
返回_db.GetCollection(“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的那一行。mongoDB自动提供默认文档ID,您只需首先找到ID,然后使用该ID查询集合 当然,您可以更改默认行为-请参阅 更改此行:
var objId = new ObjectId(id);
要执行类似的操作,必须将objectid.Parse()参数更改为您的值
var query_id = Query.EQ("_id",
ObjectId.Parse("50ed4e7d5baffd13a44d0153"));
var entity = dbCollection.FindOne(query_id);
return entity.ToString();
还有,这一行有打字错误,你是说在=符号后面有objId吗
var item = objds.GetTodoItem(objId)
学分:
您可以生成如下新对象:
ObjectId.GenerateNewId();
但很可能您在数据库中找不到任何具有该id的文档。通常,当您希望进行插入并且不希望Mongo将随机id分配给新插入的文档时,会生成ObjectId(假设您希望将该id返回给用户)
现在,假设您正在查找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);
var id=“5a71ae10a41e1656a4a50902”;
var context=newyourcontext();
var builder=Builders.Filter;
var filter=builder.Eq(x=>x.Id,ObjectId.Parse(Id));
var result=await context.TodoItemCollection.FindAsync(过滤器);
我现在明白了。我更改了我的方法,不通过ObjectID查找IDpublic-TodoItem-GetTodoItem(int-ID){var-res=Query.EQ(t=>t.TodoId,ID);返回_db.GetCollection(“TodoApi”).FindOne(res)}