json - NodeJS-ExpressJS mongoose API POST 请求带外键

标签 json node.js api express mongoose

我正在尝试使用 JSON 创建 REST API。我有 2 个模型、一个公司和一个地址。地址是企业的一部分

当我尝试使用以下 JSON 创建 POST 请求时

{
    "name" :"GRIT",
    "adress":
        {
         "street" : "test",
         "number": "5",
         "city":"leuven",
         "postalcode":"2900",
         "country":"BEL"
        }
}

我收到以下错误

{
    "error": {
        "errors": {
            "adress": {
                "message": "Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n  street: 'test',\n  number: '5',\n  city: 'leuven',\n  postalcode: '2900',\n  country: 'BEL' }\" at path \"adress\"",
                "name": "CastError",
                "stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n  street: 'test',\n  number: '5',\n  city: 'leuven',\n  postalcode: '2900',\n  country: 'BEL' }\"",
                "kind": "ObjectID",
                "value": {
                    "id": "5ad8b5e4ac4b1a443877bfc2",
                    "street": "test",
                    "number": "5",
                    "city": "leuven",
                    "postalcode": "2900",
                    "country": "BEL"
                },
                "path": "adress",
                "reason": {
                    "message": "Cast to ObjectId failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n  street: 'test',\n  number: '5',\n  city: 'leuven',\n  postalcode: '2900',\n  country: 'BEL' }\" at path \"adress\"",
                    "name": "CastError",
                    "stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n  street: 'test',\n  number: '5',\n  city: 'leuven',\n  postalcode: '2900',\n  country: 'BEL' }\"",
                    "kind": "ObjectId",
                    "value": {
                        "id": "5ad8b5e4ac4b1a443877bfc2",
                        "street": "test",
                        "number": "5",
                        "city": "leuven",
                        "postalcode": "2900",
                        "country": "BEL"
                    },
                    "path": "adress"
                }
            }
        },
        "_message": "Business validation failed",
        "message": "Business validation failed: adress: Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n  street: 'test',\n  number: '5',\n  city: 'leuven',\n  postalcode: '2900',\n  country: 'BEL' }\" at path \"adress\"",
        "name": "ValidationError"
    }
}

这些是我的 Mongoose 模型

const mongoose = require('mongoose');

const businessSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name:{
        type: String,
        required: true,
    },
    adress:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Adress',
        required:true
    }
});

module.exports = mongoose.model('Business', businessSchema);

const mongoose = require('mongoose');

const adressSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    street:{
        type: String,
        required: true
    },
    number:{
        type: int,
        required: true
    },
    city:{
        type: String,
        required: true
    },
    postalCode:{
        type: String,
        required: true
    },
    country:{
        type: String,
        required: true
    }

});

module.exports = mongoose.model('Adress', adressSchema);

以下是我的发布请求

//POST -> Register a business
router.post('/',function(req,res){



    const business = new Business({
        id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        adress:{
            id:new mongoose.Types.ObjectId(),
            street: req.body.adress.street,
            number: req.body.adress.number,
            city: req.body.adress.city,
            postalcode: req.body.adress.postalcode,
            country:req.body.adress.country
        }

    });


    business
        .save()
        .then(result => {
            console.log(result);
            res.status(201).json({
              message: "Business created"
            });
          })
          .catch(err => {
            console.log(err);
            res.status(500).json({
              error: err
            });
          });



});


module.exports = router;

我做错了什么?地址是否未保存,或者我将两个模型彼此链接错误

我使用 MongoDB 作为数据库

最佳答案

看看mongoose docs .

您正在尝试使用 Adress 对象设置 ObjectId 属性。您要做的就是首先保存您的 adress 对象,然后在您的 business 对象中引用它。

PS:您应该将您的 ID 命名为 _id,因为这是 MongoDB 中使用的约定。

它看起来像这样:

let adress = new Adress({
  _id: new mongoose.Types.ObjectId(),
  street: req.body.adress.street,
  number: req.body.adress.number,
  city: req.body.adress.city,
  postalcode: req.body.adress.postalcode,
  country: req.body.adress.country
});

adress
  .save()
  .then(() => {
    let business = new Business({
      _id: new mongoose.Types.ObjectId(),
      name: req.body.name,
      adress: adress._id
    });

    business
      .save()
      .then((result) => {
        console.log(result);
        res.status(201).json({
          message: "Business created"
        });
      });
  });

关于json - NodeJS-ExpressJS mongoose API POST 请求带外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49925070/

相关文章:

javascript - 使用 Handlebars.js,如何使用全局上下文数据填充选择框,但使用当前循环项中的数据设置选定项?

ajax - 如何提取 Google 语音数据?

javascript - 用 $http.get() 数据填充 Chart js

node.js - 如何向 Messenger Bot 的所有收件人发送通知?

javascript - html 中的快速路由变量

php - 获取 YouTube 视频缩略图并将其与 PHP 一起使用

javascript - jquery ajax 内部循环返回 statusText 错误,在 IE 中一定时间后状态为 0

node.js - react native 命令没有响应

python - python 中的 jsonify 选项卡用于 API 请求

rest - postman 将错误的整数值传递给 API Controller