NodeJS-ExpressJS 猫鼬 API POST 请求与外键

Posted

技术标签:

【中文标题】NodeJS-ExpressJS 猫鼬 API POST 请求与外键【英文标题】:NodeJS- ExpressJS mongoose API POST Request with foreign key 【发布时间】:2018-09-30 04:37:45 【问题描述】:

我正在尝试在 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 请求

//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】:

看看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"
        );
      );
  );

【讨论】:

以上是关于NodeJS-ExpressJS 猫鼬 API POST 请求与外键的主要内容,如果未能解决你的问题,请参考以下文章

猫鼬不是 $setting array.$.booleanValue 当我 findOneAndUpdate(paramOne: p, paramTwo, array.keyName: valueNa

猫鼬不是 $setting array.$.booleanValue 当我 findOneAndUpdate(paramOne: p, paramTwo, array.keyName: valueNa

我用猫鼬做这个 API Put 请求正确吗?

节点错误:找不到模块 - 我导出猫鼬模式和接口的自定义模块的 typescript api

修改猫鼬响应数据

如何在猫鼬中获取 NumberLong 记录