Sequelize 中的 findAll() 没有得到
我正在使用 Sequelize 和 MySQL.
I'm using Sequelize with MySQL.
当我运行这段代码时:
usuarioService.getAll = function () {
Usuario.findAll().then(function (users) {
//return users;
console.dir(users);
});
}
我没有得到用户,而是得到:
Instead of get the user, I get:
http://i.stack.imgur.com/uLhmN.png
请帮帮我!我要疯了!
谢谢
推荐答案
Sequelize 正在返回用户中的 instance
对象数组.instance
对象附有许多方便的方法,可让您对其进行操作.
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 使用 Promise,因此使用 Promise 进行此操作将是最好的方法.
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
});
});
相关文章