Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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"}'
share|improve this question
up vote 1 down vote accepted

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

share|improve this answer
    
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? – Faellor Jul 27 at 2:51
    
    
Thank you very much, it works now! – Faellor Jul 27 at 3:34

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.