Sequelize 中的 findAll() 没有得到 [英] findAll() from Sequelize doesn't get

查看:25
本文介绍了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
    });
});

这篇关于Sequelize 中的 findAll() 没有得到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆