0

Sorry for the long and vague title.

I am trying to add a new user to my database with an http request. I have no problem creating the tables with my model files but for some reason I can't add a new user.

So here is the error I am getting:

Executing (default): SELECT 1+1 AS result
Connection to database successfull
TypeError: Cannot read property 'user' of undefined

here is my model file user.js:

export default function createUserModel (sequelize, DataTypes) {
const user = sequelize.define('user',{
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    },
    username:{
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false
    }
},{
    classMethods: {
        associate (models){
            user.belongsToMany(models.conversation, {through:'UserConversations'});
        }
    }
});

return user;
}

The controller (user_controller.js):

var express = require('express');
var db      = require('sequelize-connect');

var router = express.Router();

router.get('/', function (req, res, next) {
    res.send('Hello World');
});

// Create new user
router.post('/', function (req, res, next) {

    try{
        const createdUser = db.models.user.create({
            email: req.body.email,
            username: req.body.username,
            password: req.body.password
        });

        res.status(200).json(createdUser.dataValues);

    }catch(err){
        console.log(err);
        next(err);
    }

});

module.exports = router;

My curl request:

curl -v -H "Content-type: application/json" -X POST http://localhost:3000/api/users/ -d '{"email":"[email protected]", "username":"test","password":"123456"}'

2 Answers 2

1

Just use return sequelize.define... instead of const user = ....

The user variable is undefined because in this case return user will be executed before the variable assignment will be finished.

Read more about asynchronous in node js.

Sign up to request clarification or add additional context in comments.

Comments

0

did you import your models to sequelize ? . There isn't user object in db.models

2 Comments

Sorry I am new to node. What do you mean by importing the models to sequelize? I can see the tables created in my postgres admin?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.