我正在尝试调试一种情况,即我似乎无法根据用户在表单字段中输入的值为我的对象创建新记录。现在我对对象创建方面的问题很感兴趣,因为帖子无法识别 .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;
Controller 索引(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>
最佳答案
你得到 Ann.create is not a function
的原因是因为你没有正确引用你的 annotation-model.js:
如果你遵循这个结构 https://stackoverflow.com/a/33981210/880709 一切都会好的,请参阅 models/index.js
和 routes/index.js
并阅读 here
关于node.js - 将 POST 方法与 Sequelize 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33989196/