我知道在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,如果不是删除不起作用,而不是简单的user.password,如果我像这样调试console.log('pass: ', user.password),我可以看到密码。
发布于 2019-11-08 23:29:25
是的,可以排除字段,就像这样:
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
发布于 2019-02-01 23:47:00
我知道这是一个古老的帖子。但我来这里是因为同样的问题,我相信会有更多的人来这里。因此,在研究了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将导致数据库中的任何查询都不返回密码。除非您使用前一个函数在查询中添加密码(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
});https://stackoverflow.com/questions/31679838
复制相似问题