通过express.sj将数据插入到mongodb时,强制转换为数组失败

时间:2018-10-15 15:58:39

标签: javascript mongodb express

我正在使用MERN堆栈制作Webiste,我已经设法将表单中的数据插入到mongodb的react前端中,但是当我制作新表单时,我得到了强制转换为数组失败的错误。我试过在我的猫鼬模型中强制转换为另一个数组,效果很好。该系统是一个模拟的网上银行,绝不能在任何生产环境中使用

我的模特:

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const Schema = mongoose.Schema;

// Creates the needed schema
let userSchema = new Schema({
  name: String,
  created_at: Date,
  updated_at: Date,
  balance: Number,
  address: String,
  ssn: Number,
  bankNumber: Number,
  cards: [
    {
      type: String, // Visa eller Mastercard
      cardNumber: Number,
      cvc: Number,
      expirationDate: Number,
      pin: Number,
      status: Boolean,
      dailyLimit: '9900'
    }
  ],
  whitdrawal: [
    {
      amount: Number,
      date: Date, // Skriv auto date logikk
      reason: String
    }
  ]
});
// Inserts
userSchema.pre('save', function(next) {
  const currentDate = new Date();
  this.updated_at = currentDate;
  this.date = currentDate;
  if (!this.created_at) this.created_at = currentDate;

  next();
});

// Creates model for schema
const AtmUser = mongoose.model('AtmUser', userSchema);

// Export so it is available for the rest of the application
module.exports = AtmUser;

用于保存此数据的快速方法,数据从前端发送并在终端错误消息中可见

app.post('/api/newUser', function(req) {
  const newUser = AtmUser({
    name: req.body.name, 
    balance: req.body.balance, 
    address: req.body.address,
    ssn: req.body.ssn, 
    bankNumber: req.body.bankNumber,
    cards: [
      { 
        type: req.body.type, // Visa eller Mastercard
        cardNumber: req.body.cardNumber,
        cvc: req.body.cvc,
        expirationDate: req.body.expirationDate,
        pin: req.body.pin,
      }
    ],
  });

  newUser.save(function(err) {
    if(err) throw err; 
    console.log('A new user has been made')
  })
})

当尝试转换为whitdrawal数组而不是纸牌数组时,一切都按预期工作,这是我在终端中收到的erorr消息的一部分

events.js:167
[0]       throw er; // Unhandled 'error' event
[0]       ^
[0] ValidationError: AtmUser validation failed: cards: Cast to Array failed for value "[ { type: '234234234' } ]" at path "cards"
[0]     at new ValidationError (/Users/andreas/Documents/prosjekt/atm/node_modules/mongoose/lib/error/validation.js:30:11)

我已经尝试发现错误了几个小时,但是找不到它,谢谢您的所有答复!如果有帮助,我很乐意发布更多代码或整个错误消息

1 个答案:

答案 0 :(得分:0)

经过反复试验,我找到了答案,结果表明类型是保留字,将其更改为formType或Type解决了我模型中的问题。

正确的模型:

app.post('/api/newUser', function(req) {
  const newUser = AtmUser({
    name: req.body.name, 
    balance: req.body.balance, 
    address: req.body.address,
    ssn: req.body.ssn, 
    bankNumber: req.body.bankNumber,
    cards: [
      { 
        formType: req.body.type, // Visa eller Mastercard
        cardNumber: req.body.cardNumber,
        cvc: req.body.cvc,
        expirationDate: req.body.expirationDate,
        pin: req.body.pin,
      }
    ],
  });

  newUser.save(function(err) {
    if(err) throw err; 
    console.log('A new user has been made')
  })
})