NodeJS- ExpressJS带有外键的mongoose API POST请求

时间:2018-04-19 15:40:03

标签: 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"
    }
}

这些是我的猫鼬模型

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作为数据库

1 个答案:

答案 0 :(得分:0)

查看mongoose docs

您正尝试使用ObjectId对象设置Adress属性。您要做的是先保存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"
        });
      });
  });