错误:SequelizeValidationError:字符串冲突:创建的不能是数组或对象

时间:2019-05-16 17:04:42

标签: mysql node.js reactjs express

我正在实施MERN堆栈登录/注册,并尝试逐步在Postman中测试我的响应。首先,我编写了用于注册的代码,然后编写了用于登录的代码,但是在调用注册链接的情况下,邮递员出现以下错误:

error: SequelizeValidationError: string violation: created cannot be an array or an object

有人可以提供任何建议帮助吗?我认为在User.js findone()函数中,我身边有些想念。

还有其他解决办法吗?

./ database / DB.js

const db = {}
const sequelize = new Sequelize("mern", "root", "", {
        host: "localhost",
        dialect: "mysql",
        port: "3307",
        operatorsAliases: false,

        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
})

db.sequelize = sequelize
db.sequelize = sequelize

module.exports = db

./ models / User.js

const db = require("../database/db")

module.exports = db.sequelize.define(
    'user',
    {
        id: {
             type: Sequelize.INTEGER,
             primaryKey: true,
             autoIncrement: true
        },
        first_name: {
            type: Sequelize.STRING
        },
        last_name: {
            type: Sequelize.STRING
        },
        email: {
            type: Sequelize.STRING
        },
        password: {
            type: Sequelize.STRING
        },
        created: {
            type: Sequelize.STRING
        }
    },
    {
        timestamps: false
    }
);

./ routes / User.js

const users = express.Router()
const cors = require('cors')
const jwt = require("jsonwebtoken")
const bcrypt = require('bcrypt')

const User = require("../models/User")
users.use(cors())

process.env.SECRET_KEY = 'secret'

users.post('/register', (req, res) => {
    const today = new Date()
    const userData = {
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email: req.body.email,
        password: req.body.password,
        created: today
    }

    User.findOne({
        where: {
            email: req.body.email
         }
    })
        .then(user => {
            if(!user){
                bcrypt.hash(req.body.password, 10, (err, hash) => {
                    userData.password = hash
                    User.create(userData)
                        .then(user => {
                            res.json({status: user.email + ' registered'})
                        })
                        .catch(err => {
                            res.send('error: ' + err)
                        })
                })  
            }   else {
                res.json({error: "User already exists"})
            }
        })
        .catch(err => {
            res.send('error: ' + err)
        })
})

users.post('/login', (req, res) => {
    User.findOne({
        where: {
            email: req.body.email
        }
    })
    .then(user => {
        if(user) {
            if(bcrypt.compareSync(req.body.password, user.password)) {
                let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
                    expiresin: 1440
                })
                res.send(token)
            }
        } else {
            res.status(400).json({error: 'User does not exist'})
        }
    })
    .catch(err => {
        res.status(400).json({ error: err})
    })
})

module.exports = users

package.json

  "name": "login-registration",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^3.0.6",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.17.2",
    "cors": "^2.8.4",
    "express": "^4.16.3",
    "jsonwebtoken": "^7.4.2",
    "mysql": "^2.14.1",
    "mysql2": "^1.6.1",
    "nodemon": "^1.18.3",
    "sequelize": "^4.38.0"
  }
}

Server.js

var cors = require ('cors')
var bodyParser = require("body-parser")
var app = express()
var port = process.env.PORT || 5000

app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))

var Users = require('./routes/users')

app.use('/users', Users)

app.listen(port, () => {
    console.log("Server is running at port: " + port)
})

3 个答案:

答案 0 :(得分:1)

此错误是由于提交的类型错误的值与 在模型中声明一个。因此,将其更改为适当的 类型是“ JSON”而不是“ STRING”。

./ models / User.js

const db = require("../database/db")

module.exports = db.sequelize.define(
    'user',
    {
        id: {
             type: Sequelize.INTEGER,
             primaryKey: true,
             autoIncrement: true
        },
        first_name: {
            type: Sequelize.STRING
        },
        last_name: {
            type: Sequelize.STRING
        },
        email: {
            type: Sequelize.STRING
        },
        password: {
            type: Sequelize.STRING
        },
        created: {
            type: Sequelize.JSON
        }
    },
    {
        timestamps: false
    }
);

答案 1 :(得分:0)

Dhaval解决方案帮了我大忙。 :)谢谢!

答案 2 :(得分:0)

在./routes/User.js中,在/ post寄存器路径下,userData对象具有一个带有Today属性的创建字段,该字段是Date对象。

在./models/User.js中,您指定创建的类型应为Sequelize.STRING。

这是导致错误的矛盾。调用User.create(userData)时,它会给您该错误,因为输入参数的类型错误。

要解决此问题,您要么需要创建一个期望的Sequlize.Date类型,要么将今天的日期对象转换为字符串。

waitpid()

Date类的字符串函数有很多不同。您应该选择最适合自己的here