Node.js Sequelizejs findAll排除字段
我知道使用Node.js Sequelizejs findAll排除字段,node.js,sequelize.js,Node.js,Sequelize.js,我知道使用选项。属性可以列出要选择的属性 但是有没有办法只排除一个字段 到现在为止,我已经和你一起解决了 User .findAll({order: [['id','DESC']]}) .then(function(users) { users = users.filter(function(user){ delete user.dataValues.password; return user; }); return reply( Repl
选项。属性可以列出要选择的属性
但是有没有办法只排除一个字段
到现在为止,我已经和你一起解决了
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
如果没有,则删除不起作用,而只是user.password
如果我像这样调试console.log('pass:',user.password)
我可以看到密码。我知道这是一篇旧文章。但我来到这里是因为同样的问题,我相信会有更多的人来。因此,在研究了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指定了此模型)。您可以这样指定字段:密码:{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
});
是的,可以排除字段,如下所示:
User
.findAll({
attributes: {exclude: ['password']},
order: [['id','DESC']]})
.then( users => {
return reply( ReplyUtil.ok(users) );
})
.catch( err => {
return reply( ReplyUtil.badImplementation(err) );
});
有关更多详细信息,请参阅