我有办法解决Nodejs和Postgresql中的这个问题吗?

时间:2019-11-20 06:32:16

标签: node.js postgresql express

我正在尝试将一些数据发送到PostgreSQL数据库中,但出现此错误:

connected to the database
{ error: null value in column "firstname" violates not-null constraint
    at Connection.parseE (F:\expressApi\node_modules\pg\lib\connection.js:604:11)
    at Connection.parseMessage (F:\expressApi\node_modules\pg\lib\connection.js:401:19)
    at Socket.<anonymous> (F:\expressApi\node_modules\pg\lib\connection.js:121:22)
    at Socket.emit (events.js:182:13)
    at addChunk (_stream_readable.js:283:12)
    at readableAddChunk (_stream_readable.js:264:11)
    at Socket.Readable.push (_stream_readable.js:219:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'error',
  length: 214,
  severity: 'ERROR',
  code: '23502',
  detail: 'Failing row contains (6, null, null, null, null, null).',
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: 'public',

和下面是我正在使用的代码:

userController.js

const { create } = require('./user.service');
//const { genSaltSync, hashSync } = require('bcrypt');


module.exports = {
    createUser: (req, res) => {
        const body = req.body;
        console.log(body)
            // const salt = genSaltSync(10);
            //body.password = hashSync(body.password, salt);
        create(body, (err, results) => {
            if (err) {
                console.log(err);
                return res.status(500).json({
                    success: 0,
                    message: "Database connection error"
                });
            }
            return res.status(200).json({
                success: 1,
                data: results
            })
        })
    }
}

userService.js

const pool = require('../../config/database');

pool.on('connect', () => {
    console.log('connected to the database');
})

module.exports = {
    create: (data, callBack) => {
        pool.query(
            // 'insert into registration(firstname, lastname, gender, email, password) values($1, $2, $3, $4, $5)'
            `insert into registration(firstname, lastname, gender, email, password)
            values($1, $2, $3, $4, $5)`, [
                data.first_name,
                data.last_name,
                data.gender,
                data.email,
                data.password
            ],
            (error, results, fields) => {
                if (error) {
                    return callBack(error);
                }
                return callBack(null, results);
            }
        );
    }
}

有什么帮助吗?

0 个答案:

没有答案
相关问题