【问题标题】:MongoDB C# BsonRepresentation of an Array of ObjectIdsMongoDB C# BsonRepresentation of ObjectIds 数组
【发布时间】:2012-05-28 08:22:36
【问题描述】:

我有这样的文件方案:

{
  "_id" : ObjectId("4fbb728d80db260988580e05"),
  "titleFull" : "Foo, Inc",
  "titleShort" : "Foo",
  "countries" : [
     ObjectId("4fba04ef80db260988f8b607"),
     ObjectId("4fba05f880db260988cd5cfd") ],
  "type" : "company"
}

以及 ASP.NET MVC 4 Web API 项目中的此类:

public class Company
{
  [BsonRepresentation(BsonType.ObjectId)]
  public String id { get; set; }
  public String titleFull { get; set; }
  public String titleShort { get; set; }
  //[BsonRepresentation(BsonType.ObjectId)]
  //public String[] countries { get; set; } — not working
  public ObjectId[] countries { get; set; }
  public String type { get; set; }
}

当我在/api/countries 上发送 GET 请求时,我收到 JSON 文档(它是 mvc 反序列化):

{
  "id": "4fba097e80db2609886ce7f2",
  "titleFull": "Foo, LLC",
  "titleShort": "Foo",
  "countries": [
    {
      "_increment": 16299527
      "_machine": 8444710
      "_pid": 2440
      "_timestamp": 1337591023
    },
    {
      "_increment": 13458685
      "_machine": 8444710
      "_pid": 2440
      "_timestamp": 1337591288
    }
  ],
  "type": "company"
}

有没有办法像这样进行 JSON 响应:

{
  "id": "4fba097e80db2609886ce7f2",
  "titleFull": "Foo, LLC",
  "titleShort": "Foo",
  "countries": ["4fba04ef80db260988f8b607","4fba05f880db260988cd5cfd"],
  "type": "company"
}

【问题讨论】:

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


    【解决方案1】:

    致未来读者的注意事项

    Rober Stam 在 google 群组中写道:

    反序列化代码中存在错误。在数组的情况下,[BsonRepresentation] 属性实际上应用于项目而不是数组。

    我为此创建了一个 JIRA 票证:

    https://jira.mongodb.org/browse/CSHARP-479

    所以如果你有同样的问题,请追踪这张票。

    【讨论】:

    • 好的,谢谢。我将删除我的答案,因为它目前不正确。
    【解决方案2】:

    在响应中,不要使用 ObjectId 来表示国家,而是使用字符串数组并添加要在 json 响应中传递的 id。

    公共字符串[]国家{得到;放; }

    如果你像这样使用,响应在 json 中会是这样的

    “国家”:[“4fba04ef80db260988f8b607”,“4fba05f880db260988cd5cfd”],

    您正在使用 id 字段中已有的字符串。

    【讨论】:

    • id 中的字符串是[BsonRepresentation(BsonType.ObjectId)] 注释反序列化的结果。
    • 我不能使用string的数组,因为我已经有了ObjectIds数组的方案
    • 你需要一个ObjectId的数组吗?
    • 在 MongoDB 中我想要一个 ObjectIds 的数组,但在应用程序中更方便地接收带有 Strings 数组的 JSON 对象
    • 如果必须使用对象 ID,则必须在 json 响应中使用它,或者在 json 响应中返回字符串数组。
    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多