【问题标题】:nodejs get all users and return users only name, id, image not all datanodejs获取所有用户并仅返回用户名称,ID,图像不是所有数据
【发布时间】:2020-07-21 01:07:28
【问题描述】:

我想获取所有用户的姓名、头像、身份证,但 find() 返回该用户的所有数据,如密码、地址等,但我只想要姓名、身份证、头像。这是我的代码

User.find()
.then(data => {

if (data==0) {
  res.status(500).send({
      message:"There are no user"
  });
}else{
  res.status(200).send( data );
}
  
})
  .catch(err => {
res.status(500).send({
  message:
    err.message || "Some error occurred while retrieving tutorials."
});
});

【问题讨论】:

  • 您可以创建一个 DTO(数据传输对象),它通过您在 user.service 中定义的相同 id 引用该对象,但只保存您想要获取的参数。例如像这样: // // export class User { id: string, username: string, password: string, moreInfo: string } // // 导出 class UserDto { id: string, username: string, moreInfo: string }。然后,您创建 2 个服务函数,分别获取一个 dto 和一个在需要时获取整个用户的服务函数
  • 感谢您的回答。但我得到了另一个解决方案mongoosejs.com/docs/api.html#query_Query-select 使用这个我可以选择特定的字段,比如这个 User.find().select('name _id image')。

标签: node.js angular mongodb


【解决方案1】:

我希望你也使用猫鼬。

User.find({}, 'firstName lastName picture', function(error, data) {
if (error) {
    return res.status(500).send({
        msg: 'Error while finding records',
        data: []
    })
} else {
    return res.send(200).send({
            msg: 'recods found',
            data: data
        })
  }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多