【问题标题】:Can't get documents by ID in MongoDB Web API无法在 MongoDB Web API 中按 ID 获取文档
【发布时间】:2017-05-25 10:55:37
【问题描述】:

我的 Get 请求允许我通过 ID 获取我的集合中的第一个文档,但不允许我通过 ID 获取任何其他文档,因此它只返回 ID 或 null 的第一个文档。我还有一个 GetAll 请求以返回我的数据库中的所有 1000 个文档,这似乎有效。

这是我的代码:

在控制器中获取请求:

 // GET api/something/id
    [HttpGet]
    public HttpResponseMessage Get(string id)
    {

        var something = _somethingService.Get(id);
        if (something != null)
        {
            return Request.CreateResponse(HttpStatusCode.OK, something);

        }
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Nothing for provided id.");
    }

东西模型:

public class SomethingsModel
{
    [BsonElement("_id")]
    [BsonRepresentation(BsonType.String)]
    public ObjectId id { get; set; }

    public string SomethingId
    {
        get { return id.ToString(); }
        set { id = ObjectId.Parse(value); }
    }

    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("description")]
    public string Description { get; set; }
    //[BsonElement("category")]
    //public string Category { get; set; } 

    [BsonElement("address")]
    public AddressModel Address { get; set; }

    [BsonElement("latlong")]
    public LatLongModel LatLong { get; set; }

    [BsonElement("price")]
    public int Price { get; set; }

    [BsonElement("rating")]
    public int Rating { get; set; }

    [BsonElement("photourl")]
    public string PhotoUrl { get; set; }

}

东西服务:

 public class SomethingService : ISomethingService
{
    private readonly SomethingsUnitOfWork _sUnitOfwork;

    public SomethingService()
    {
        _sUnitOfwork = new SomethingsUnitOfWork();
    }

    public SomethingsModel Get(string id)
    {
        return _sUnitOfwork.Somethings.Get(id);
    }

    public IQueryable<SomethingsModel> GetAll()
    {
        return _sUnitOfwork.Somethings.GetAll();
    }

    public void Delete(string id)
    {
        _sUnitOfwork.Somethings.Delete(s => s.SomethingId, id);
    }

    public void Insert(SomethingsModel something)
    {
        _sUnitOfwork.Somethings.Add(something);
    }

    public void Update(SomethingsModel something)
    {
        _sUnitOfwork.Somethings.Update(s => s.SomethingId, something.SomethingId, something);
    }

}

SoemthingsRepository:

public class SomethingsRepository<T> where T : class
{
    private MongoDatabase _database;
    private string _tableName;
    private MongoCollection<T> _collection;

    // constructor to initialise database and table/collection  
    public SomethingsRepository(MongoDatabase db, string tblName)
    {
        _database = db;
        _tableName = tblName;
        _collection = _database.GetCollection<T>(tblName);
    }


    /// <summary>
    /// Generic Get method to get record on the basis of id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public T Get(string id)
    {
        return _collection.FindOneById(id);

    }

    /// <summary>
    /// Get all records 
    /// </summary>
    /// <returns></returns>
    public IQueryable<T> GetAll()
    {
        MongoCursor<T> cursor = _collection.FindAll();
        return cursor.AsQueryable<T>();

    }

    /// <summary>
    /// Generic add method to insert enities to collection 
    /// </summary>
    /// <param name="entity"></param>
    public void Add(T entity)
    {
        _collection.Insert(entity);
    }

    /// <summary>
    /// Generic delete method to delete record on the basis of id
    /// </summary>
    /// <param name="queryExpression"></param>
    /// <param name="id"></param>
    public void Delete(Expression<Func<T, string>> queryExpression, string id)
    {
        var query = Query<T>.EQ(queryExpression, id);
        _collection.Remove(query);
    }

    /// <summary>
    ///  Generic update method to delete record on the basis of id
    /// </summary>
    /// <param name="queryExpression"></param>
    /// <param name="id"></param>
    /// <param name="entity"></param>
    public void Update(Expression<Func<T, string>> queryExpression, string id, T entity)
    {
        var query = Query<T>.EQ(queryExpression, id);
        _collection.Update(query, Update<T>.Replace(entity));
    }

}




And

我的文档架构:

{
"_id": {
    "$oid": "591593fbb2c2a737588dbbcc"
},
"name": "Kulas Inc",
"description": "Bypass Esophag to Duoden with Synth Sub, Perc Endo Approach",
"address": {
    "lineone": "9 Leroy Terrace",
    "city": "Afonsoeiro",
    "country": "Portugal",
    "postcode": "2870-013"
},
"latlong": {
    "latitude": "38.7",
    "longitude": "-8.9167"
},
"price": 61,
"rating": 70,
"photourl": "http://dummyimage.com/160x221.jpg/dddddd/000000"
}

为代码量道歉。我不确定为什么我能够在我的集合中获得第一个文档,但其他文档都没有。我感觉我的代码中存在序列化问题,或者我的 _id 嵌套在每个文档中?

【问题讨论】:

  • 它不是“嵌套的”,而是转储中的 JSON 序列化程序如何表示 ObjectId。价值是如何发送的?作为这样的“字符串”"591593fbb2c2a737588dbbcc"?传入的值是否与数据库中的文档实际匹配?是我的眼睛还是你实际上没有显示应该传入这个值的get方法?
  • findOneById 是否将字符串转换为 ObjectId?可能没有。

标签: c# mongodb asp.net-web-api


【解决方案1】:

您的实体的 id 类型为 ObjectId。当您从数据库中获取实体时,您应该使用这种类型而不是字符串:

public T Get(string id)
{
    return _collection.FindOneById(ObjectId.Parse(id));
}

注意事项:

  • 您可以使用小写约定和 BsonClassMap 来默认存储所有小写的元素。
  • MongoDb 使用 _id 名称作为标识字段。您无需手动指定。
  • 您可以将方法的返回类型更改为IHttpActionResult,并使用ApiController 中的Ok 和NotFound 方法来创建适当的操作结果。

【讨论】:

  • 抱歉,我的解释有点混乱。我的意思是我可以通过 ID 获取集合中的第一个文档,但如果我尝试获取任何其他文档,它会返回 null
  • @Powellellogram 好的,知道了
猜你喜欢
  • 2017-02-17
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 2019-08-18
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多