问题
I'm using Sequelize with MySQL.
When I run this code:
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
Help me, please! I'm going crazy!
Thanks
回答1:
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.
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').
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.
Edit
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)
});
});
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
});
});
回答2:
You are returning a user.
The first bit you see is the SQL query that Sequelize is executing for you.
The bit that says
dataValues:
{ usuario_id: 1,
...
}
is your user. findAll() should give you an array with all of your users.
If you just want the dataValues returned you can just pass in raw: true.
usuarioService.getAll = function () {
Usuario.findAll({ raw: true }).then(function (users) {
//return users;
console.dir(users);
});
}
来源:https://stackoverflow.com/questions/36214221/findall-from-sequelize-doesnt-get