无法在我的续集模型上执行任何操作
问题描述:
我正在开发一个简单的项目,使用sequelize + mysql + express,因为一个简单的问题而陷入困境:无法执行使用我的模型的findById等功能。无法在我的续集模型上执行任何操作
对于下面的代码,我得到了“db.usuario.findById(...)。exec不是函数”消息。我是新手。
这是我的模型:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('usuario', {
id_Usuario: {
type: DataTypes.STRING(18),
allowNull: false,
primaryKey: true
},
tipo: {
type: DataTypes.STRING(1),
allowNull: false
},
nome: {
type: DataTypes.STRING(45),
allowNull: false
},
matricula: {
type: DataTypes.STRING(45),
allowNull: false,
unique: true
},
telefone: {
type: DataTypes.STRING(15),
allowNull: true
},
cpf: {
type: DataTypes.STRING(11),
allowNull: false,
unique: true
},
email: {
type: DataTypes.STRING(45),
allowNull: false,
unique: true
},
senha: {
type: DataTypes.STRING(45),
allowNull: false
},
instituicaoEnsino: {
type: DataTypes.STRING(45),
allowNull: false
}
}, {
tableName: 'usuario'
});
};
这是我的控制器:
var db = require('../db');
exports.user_edit_get = function(req, res, next) {
async.parallel({
user: function(callback) {
db.usuario.findById(req.params.id)
.exec(callback)
},
}, function(err, results) {
if (err) { return next(err); }
//Successful, so render
res.render('usuarioDetalhes', { user });
});
}
我db.js文件:
var Sequelize = require('sequelize');
const sequelize = new Sequelize('mydb', 'root', '[email protected]', {
host: 'localhost',
port: '3306',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
// Connect all the models/tables in the database to a db object,
//so everything is accessible via one object
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
//Models/tables
db.usuario = require('./models/usuario.js')(sequelize, Sequelize);
module.exports = db;
答
此代码似乎是一个混合物, Sequelize和Mongoose,它们都有一个名为findById
的方法:
db.usuario.findById(req.params.id)
.exec(callback)
猫鼬使用exec
,而Sequelize方法findById
将返回一个Promise。真的没有任何需要使用async.parallel
,你可以使用Promise.all
而不是(我假设你的真实代码包含多个查询,如果你真的只有1,那么你不需要任何这个)。
如果你做到这一点使用async.parallel
它可能是这个样子:
async.parallel({
user: function(callback) {
db.usuario.findById(req.params.id).then(
function(value) {
callback(null, value);
},
function(err) {
callback(err);
}
);
}
}, ...