cphill cphill - 1 month ago 12
Node.js Question

Using the POST method with Sequelize

I'm trying to debug a situation where I can't seem to create a new record for my object based on the values the user inputs into the form fields. Right now I'm getting hung up on the object creation aspect where the post isn't recognizing the

.create
. Should I be also be using
.create
or
.build
? I tried both and the same error occurred.

TypeError: Ann.create is not a function
at /Users/user/Desktop/Projects/node/nodeapp/app/controllers/appRoutes.js:13:20


appRoutes.js:

var express = require('express');
var appRoutes = express.Router();
var Annotation = require('../models/annotation-model');

appRoutes.route('/')

.get(function(req, res){
res.render('pages/activity-feed.hbs');
})

.post(function(req, res){

var annotation = new Annotation.create({

annotation_date: req.body.annotation-date,

}).then(function(user){
console.log(user.get({plain:true}))
});



annotation.save(function(err){
if (err)
res.send(err);
});
});

module.exports = appRoutes;


Controller index (dbIndex.js):

var Sequelize = require('sequelize');
var sequelize = new Sequelize('test', 'admin', 'pwd', {
host:'localhost',
port:'3306',
dialect: 'mysql'
});

sequelize
.authenticate()
.then(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
});

var db = {}

db.Annotation = sequelize.import(__dirname + "/annotation-model");

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;


annotation-model.js:

module.exports = function(sequelize, DataTypes) {

var Annotation = sequelize.define('table', {
annotation_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
annotation_date: DataTypes.DATE,
}, {
freezeTableName: true
});
return Annotation;
}


form for POST method (activity-feed.hbs):

<div class="row">
<div class="col-md-6 col-md-offset-3" style="background-color:#ffe680;">
<div class="annotation-form">
<img class="media-object" src="http://placehold.it/80x80" alt="Generic placeholder image">
<form action="/app" method="post">
<label for="annotation-date">Annotation Date:</label>
<br />
<button>Create</button>
</form>
</div>
</div>
</div>

Answer

There were two parts to the solution to this issue. Both parts are found within the appRoutes.js file.

  1. var models should point to the dbIndex.js file and not where the model is defined (annotation-model.js). var models = require('../models/dbIndex);

  2. You must specify the object within the dbIndex so that we can use the .create method. This means models.Annotation.create()