Mongoose + MongoDB-尝试使用POSTMAN保存后,强制转换为ObjectID的值失败

时间:2019-02-24 15:44:27

标签: javascript node.js mongodb mongoose

我正在尝试在mongoDB中保存一个引用其他2个对象的对象,但是我没有得到它。每当我尝试时,都会收到此消息。

为此,它使用POSTMAN来测试我正在创建的API。

{
    "message": "Order validation failed: payments.0.credit_card.card: Cast to ObjectID failed for value \"{ number: '4898308633754712',\n  holder_name: 'Test test',\n  exp_month: 1,\n  exp_year: 2022,\n  cvv: '1234' }\" at path \"credit_card.card\", customer: Cast to ObjectID failed for value \"{ name: 'Test Test', email: 'test@gmail.com' }\" at path \"customer\""
}

我要保存在mongoDB中的json对象:

{
  "items": [{
    "name": "Plano s",
    "amount": 12345,
    "description": "Descrição do Plano Sanarflix",
    "quantity": 1
  }],
  "customer": {
    "name": "Test Test",
    "email": "test@gmail.com"
  },
  "payments": [{
    "payment_method": "credit_card",
    "credit_card": {
        "installments":1,
        "capture": true,
      "card": {
        "number": "4898308633754712",
        "holder_name": "Test Test",
        "exp_month": 1,
        "exp_year": 2022,
        "cvv": "1234"
      }
    }
  }]
}

这是我定义的模型顺序:

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Model for order
const schema = new Schema({
    customer: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Customer',
        required: function(){
            return this.customer_id;
        }        
    },
    items: [{
        amount: {
            type: Number,
            required: true
        },
        description: {
            type: String,
            trim: true
        },
        quantity: {
            type: Number,
            required: true
        }
    }],
    payments: [{
        payment_method: {
            type: String,
            required: true,
            trim: true
        },
        credit_card: {
            installments: {
                type: Number,
                default: 1
            },
            capture: {
                type: Boolean,
                default: true
            },
            card: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'Card'
            }  
        },
    }]
});

module.exports = mongoose.model('Order', schema);

这有什么问题?因为当我使用Studio3 Mongo Manager将相同的json导入MongoDB时,可以保存它并以正确的方式查看对象。

1 个答案:

答案 0 :(得分:0)

引用其他2个对象的对象,是的,ObjectId引用了,但是您要传递整个对象。

三个选项:

  • 传递idcustomer对象的card(如果它们已经存在)
  • 将这些新数据插入各自的馆藏中然后使用创建的ID(可能是 the 解决方案)插入订单
  • 将您的架构重写为仅包含Order集合,该集合可以容纳所有内容(不是很好)。

此外,让卡号在服务器中传输是非常危险的(从法律上来讲)(特别是如果您要存储它们的话)...请查看您正在实施的付款服务如何处理交易:在任何体面的服务上,服务器永远看不到银行数据,从而使您的公司不承担任何责任。