如何使用环回为 mongodb 创建 post API

How to make a post API for mongodb with loopback

我是 mongodbloopback 的新手。我想将数据从我的应用程序发送并保存到数据库。我该怎么做?

更新 店铺型号:

{
  "shopname": "string",
  "tel": "string",
  "latlng": "string",
  "address": "string",
  "id": "string",
  "personId": "string"
}

卷曲:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \ 
   "shopname": "spring", \ 
   "tel": "12345678", \ 
   "latlng": "52.1106986,21.7768998", \ 
   "address": "05-319 Skwarne, Poland" \ 
 }' 'http://localhost:3000/api/shops'

现在我应该在 shops.js 中写些什么来提供 api 以便在应用程序中使用将数据发送到数据库?

'use strict';

    module.exports = function(Shops) {

    };

您应该提供有关您已完成的步骤的更多信息。 让我从第一步开始:

  1. 在您的服务器上下载并安装 mongodb:link

  2. 在 运行 mongodb 之后,将您想要的数据库信息添加到 datasources.json 文件。例如

    {
        "db": {
        "name": "db",
        "connector": "memory"
        },
        "shopDB": {
        "host": "localhost",
        "port": 27017,
        "url": "mongodb://localhost:27017/shopDB",
        "database": "shopDB",
        "password": "",
        "name": "shopDB",
        "user": "",
        "connector": "mongodb"
        }
    }
    
  3. 通过 npm 将 loopback-connector-mongodb 添加到您的项目中。

  4. 现在定义您的模型(您可以利用 loopback 的用户友好命令行界面来执行此操作。在项目根文件夹中调用命令 "slc loopback:model")

  5. 完成第 4 步后,loopback 将为您创建 2 个文件:shop.js 和 shop.json => 这些文件位于您的 projectFolder/common/models/目录。请注意,在命名模型时遵循环回的约定并以单数形式命名您的模型(商店)是一种很好的做法。 (它在项目的其他部分使用模型名称的复数形式)。您的 shop.json 应类似于以下代码:

    {
        "name": "shop",
        "plural": "shops",
        "base": "PersistedModel",
        "idInjection": true,
        "options": {
            "validateUpsert": true
        },
        "properties": {
            "shopname": {
                "type": "string",
                "required": true
            },
            "tel": {
                "type": "string",
                "required": true
            },
            "latlng": {
                "type": "string",
                "required": true
            },
            "address": {
                "type": "string"
            },
            "personId": {
                "type": "string",
                "required": true
            }
        },
        "validations": [],
        "relations": {},
        "acls": [],
        "methods": {}
    }
    
  6. 现在您可以 post 您的商店 json 到 http://localhost:3000/api/shops/ 。请注意,我们的商店模型继承自 PersistedModel 基本模型,并具有一些内置函数来执行 crud 操作。如果您只想在数据库中创建一些商店实例,则无需向 shop.js 文件添加任何内容!