我知道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)
,则可以看到密码。
我知道这是旧帖子。但是由于同样的问题,我来到这里,我相信会有更多的人来。因此,在研究了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) );
});
另一种方法是更改模型(通过代码,我假设您用猫鼬或后继指定了此模型)。您可以像这样指定字段: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
});
是,可以排除字段,就像这样: