U
U
uib2018-10-25 08:09:25
JavaScript
uib, 2018-10-25 08:09:25

Cannot read property 'findOne' of undefined?

When creating a new user, the following error occurs:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'findOne' of undefined

controller:
const bcrypt = require('bcryptjs')
const db = require('../config/db.config.js')
const User = db.users
const errorHandler = require('../utils/errorHandler')

module.exports.register = async function(req, res) {
    const candidate = await User.findOne({
        where: {
            username: req.body.username
        }
    })

    if (candidate) {
        res.status(409).json({
            message: 'Такой login уже занят. Попробуйте другой.'
        })
    } else {
        const salt = bcrypt.genSaltSync(10)
        const password = req.body.password
        const user = new User({
            name: req.body.name,
            username: req.body.username,
            roles: req.body.roles,
            password: bcrypt.hashSync(password, salt),
            photoSrc: req.file ? req.file.path: ''
        })
        try {
            await user.save()
            res.status(201).json(user)
        } catch(e) {
            errorHandler(res, e)
        }
    }
}

models:
module.exports = (sequelize, Sequelize) => {
    const User = sequelize.define('users', {
      name: {
            type: Sequelize.STRING(100),
            required: true
      },
      username: {
            type: Sequelize.STRING(40),
            required: true,
            unique: true
      },
      roles: {
            type: Sequelize.STRING(100),
            required: true
      },
      password: {
            type: Sequelize.STRING(100),
            required: true
        },
        photoSrc: {
            type: Sequelize.STRING(200),
            default: ''
        }
    });

    return User;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom, 2018-10-25
@dexes56

Apparently, there is no users field in the db variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question