ID из базы данных не используется в API - PullRequest
0 голосов
/ 06 июня 2019

Я создал API, используя Loopback, и подключил его к MongoDB. Я загрузил некоторые данные в свою базу данных через файл JSON, и я могу получить к ним доступ без проблем.

Данные целиком (доступны из GET / fish)

[
  {
    "name": "Walleye",
    "scientific": "Sander Vitreus",
    "environment": "Fresh Water",
    "minClimate": "0",
    "maxClimate": "0",
    "minDepth": "0",
    "maxDepth": "27",
    "avLength": "54",
    "maxLength": "107",
    "avWeight": "0",
    "maxWeight": "11.3",
    "maxAge": "29",
    "description": "Occurs in lakes, pools, backwaters, and runs of medium to large rivers. Frequently found in clear water, usually near brush. Prefers large, shallow lakes with high turbidity. Rarely found in brackish waters. Feeds at night, mainly on insects and fishes (prefers yellow perch and freshwater drum but will take any fish available) but feeds on crayfish, snails, frogs, mudpuppies, and small mammals when fish and insects are scarce. Although not widely farmed commercially for consumption, large numbers are hatched and raised for stocking lakes for game fishing. Utilized fresh or frozen; eaten pan-fried, broiled, microwaved and baked.",
    "id": "1"
  },
  {
    "name": "Northern Pike",
    "scientific": "Esox Lucius",
    "environment": "Fresh Water",
    "minClimate": "10",
    "maxClimate": "28",
    "minDepth": "1",
    "maxDepth": "5",
    "avLength": "55",
    "maxLength": "137",
    "avWeight": "0",
    "maxWeight": "28.4",
    "maxAge": "30",
    "description": "Occurs in clear vegetated lakes, quiet pools and backwaters of creeks and small to large rivers. Usually solitary and highly territorial. Enters brackish water in the Baltic. Adults feed mainly on fishes, but at times feed heavily on frogs and crayfish. Cannibalism is common. In arctic lakes, it is sometimes the only species present in a given water body. In such cases, juveniles feed on invertebrates and terrestrial vertebrates; large individuals are mainly cannibals. Cannibalistic as juveniles. Feces of pike are avoided by other fish because they contain alarm pheromones. Deposits feces at specific locations, distant from its foraging area. Eggs and young are preyed upon by fishes, aquatic insect larvae, birds, and aquatic mammals. Does not generally undertake long migrations, but a few may move considerable distances. This fish can be heavily infested with parasites, including the broad tapeworm which, if not killed by thorough cooking, can infect human; is used as an intermediate host by a cestode parasite which results to large losses in usable catches of lake whitefish (Coregonus clupeaformis) in some areas; also suffers from a trematode which causes unsightly cysts on the skin. Excellent food fish; utilized fresh and frozen; eaten pan-fried, broiled, and baked. Valuable game fish. In spite of numerous attempts to culture this species, it was never entirely domesticated and does not accept artificial food. Locally impacted by habitat alterations",
    "id": "2"
  }
]

Но если я пытаюсь получить доступ к одной коллекции с помощью команды /fish/{id}, я получаю сообщение об ошибке! Ошибка:

{
  "error": {
    "statusCode": 404,
    "name": "Error",
    "message": "Unknown \"fish\" id \"\"1\"\".",
    "status": 404,
    "code": "MODEL_NOT_FOUND",
    "stack": "Error: Unknown \"fish\" id \"\"1\"\".\n    at ... (removed long path)... 
  }
}

Как правильно получить доступ к одной коллекции? Используя петлю, мне нужно будет добавить каждую отдельную рыбу как модель петли? Мне кажется, это то, что говорит эта ошибка?

1 Ответ

0 голосов
/ 07 июня 2019

Итак, я понял это сегодня вечером.

Сначала мне пришлось отредактировать файл JSON в моем API

"idInjection": false, //change from true to false 
"properties": {
    "_id": { //add an id field to the properties
      "type": "string",
      "id": true,
      "generated": true
    },

Затем мне пришлось изменить данные JSON, которые я загрузил в свою базу данных. Вместо использования целых чисел (1, 2, 3 и т. Д.) Мне пришлось использовать строки. Так что для моей Walleye модели я сменил

"_id": "1"

до

"_id": "walleye"

Теперь я могу без проблем использовать команду GET / fish / {id}! Надеюсь, что это помогает всем, кто сталкивается с этим.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...