【问题标题】:Sequelizejs findAll exclude field续集 findAll 排除字段
【发布时间】:2015-07-28 14:50:10
【问题描述】:

我知道options.attributes 您列出了您想要选择的属性 但是有没有办法只排除一个字段?

现在我已经解决了

User
  .findAll({order: [['id','DESC']]})
  .then(function(users) {
    users = users.filter(function(user){
      delete user.dataValues.password;
      return user;
    });
    return reply( ReplyUtil.ok(users) );
  })
  .catch(function(err){
    return reply( ReplyUtil.badImplementation(err) );
  });

顺便说一句

我不明白为什么你应该使用user.dataValues.password if not delete 不起作用,而不是简单地 user.password 如果我像这样调试console.log('pass: ', user.password)我可以看到密码。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    是的,可以排除字段,就像这样:

    User
      .findAll({
        attributes: {exclude: ['password']},
        order: [['id','DESC']]})
      .then( users => {
        return reply( ReplyUtil.ok(users) );
      })
      .catch( err => {
        return reply( ReplyUtil.badImplementation(err) );
      });
    

    更多详情见https://sequelize.org/master/manual/querying.html

    【讨论】:

      【解决方案2】:

      我知道这是一篇旧帖子。但是我是因为同样的问题才来到这里的,我相信会有更多的人来。所以,研究了stackoverflow这里的一些帖子后,我发现最简单的方法是使用select函数来指定我们不想返回的字段。所以它的功能应该是这样的:

      User
        .findAll({order: [['id','DESC']]}).select('-password')
        .then(function(users) {
          return reply( ReplyUtil.ok(users) );
        })
        .catch(function(err){
          return reply( ReplyUtil.badImplementation(err) );
        });
      

      另一种方法是更改​​模型(通过代码,我假设您使用 mongoose 或 sequelize 指定了此模型)。您可以像这样指定字段:password: { type: String, select: false }。默认情况下,此选择将​​导致密码不会被数据库中的任何查询返回。除非你使用前面的函数在查询中添加密码(select ('+ password'))。

      为了回答您的主要问题,Mongoose 和 Sequelize 将其所有返回值包装在包含元数据的虚拟对象中。如果您有一个对象,而您只想要未装饰的对象,则必须打开它们,如下所示:

      Model.findById(1).then(data => {
        console.log(data.get({ plain: true }));
      });
      

      如果您只想打印对象,可以使用 .toJSON:

      Model.findById(1).then(data => {
        console.log(data.toJSON);
      });
      

      如果你只想要数据而不是模型实例,你可以这样做:

      Model.findAll({
        raw: true
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-15
        • 2016-05-21
        • 2019-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 2011-10-26
        相关资源
        最近更新 更多