使用Sequelize的POST方法

时间:2015-11-29 23:01:58

标签: node.js express sequelize.js

我正在尝试调试一种情况,根据用户输入表单字段的值,我似乎无法为对象创建新记录。现在我正忙于对象创建方面,其中帖子没有识别.create。我是否也应该使用.create.build?我试过两个,发生了同样的错误。

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;

控制器索引(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;

注释-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;
}

POST方法的表单(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>

2 个答案:

答案 0 :(得分:0)

您获得Ann.create is not a function的原因是因为如果您遵循此结构,annotation-model.js:没有正确的引用https://stackoverflow.com/a/33981210/880709一切都会好的,请参阅models/index.jsroutes/index.js加上阅读here

答案 1 :(得分:0)

这个问题的解决方案分为两部分。这两个部分都在appRoutes.js文件中找到。

  1. var models应指向dbIndex.js文件,而不是指定模型的位置(annotation-model.js)。 var models = require('../models/dbIndex);

  2. 您必须在dbIndex中指定对象,以便我们可以使用.create方法。这意味着models.Annotation.create()