来自Sequelize的findAll()没有得到 [英] findAll() from Sequelize doesn't get
问题描述
我正在使用Sequelize与MySQL。
I'm using Sequelize with MySQL.
当我运行此代码时:
usuarioService.getAll = function () {
Usuario.findAll().then(function (users) {
//return users;
console.dir(users);
});
}
我得到:
http://i.stack.imgur.com/uLhmN.png
请帮帮我!我疯了!
谢谢
推荐答案
Sequelize回归用户中的实例
对象数组。一个实例
对象附加了许多方便的方法,允许你对它采取行动。
Sequelize is returning an array of instance
objects in users. An instance
object has a number of convenience methods attached to it that allow you to act on it.
如果你想要只使用字段作为键获取数据,请使用 get({plain:true})
。例如,对于数组中的第一个对象 users [0] .get({plain:true})
。如果要继续使用实例,可以使用带有字段名称的get。例如, users [0] .get('nombre')
。
If you want to get just the data with your fields as keys, use get({plain: true})
. For example, for the first object in the array users[0].get({plain: true})
. If you want to keep using the instances, you can just use get with the name of your field. For example, users[0].get('nombre')
.
您应该也可以访问直接在对象上的属性,即使它们没有被记录,例如 users [0] .nombre
。
You should be also able to access the properties directly on the object, even if they're not being logged, such as users[0].nombre
.
这与原始问题无关,但您对其他答案的评论。确保你是异步做事。代码应该是:
This is not related to the original question, but your comment on another answer. Make sure you are doing things asynchronously. The code should be:
usuarioService.getAll = function (cb) {
Usuario.findAll().then(function (users) {
return cb(null, users);
}).catch(function(err) {
return cb(err);
});
}
然后在调用此方法时,您会执行以下操作:
Then when calling this method you would do something like:
router.get('your_path', function(req, res, next) {
serv.getAll(function(err, users) {
if (err) {
// your err handling code
}
// users is now a valid js array
// could send it in res.json(users)
});
});
或
由于Sequelize使用了承诺,使用promises这样做是最好的方法。
or
Since Sequelize uses promises, doing this using promises would be the best way.
usuarioService.getAll = function () {
return Usuario.findAll({ raw: true });
}
然后在调用此方法时,您会执行以下操作:
Then when calling this method you would do something like:
router.get('your_path', function(req, res, next) {
serv.getAll().then(function(users) {
res.render('usuarios/index',{
users: users
})
}).catch(function(err) {
// your error handling code here
});
});
这篇关于来自Sequelize的findAll()没有得到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!