简体   繁体   English

如果在mongo集合中找不到ID,如何将响应发送给客户端?

[英]How to send response to client if id could not find in mongo collection?

I am working on user authentication when user hit the application and is not part of user management collection i want to send user id to client so he can request access. 当用户点击应用程序但不属于用户管理集合时,我正在进行用户身份验证,我想将用户ID发送给客户端,以便他可以请求访问权限。 we are getting user information using csp cookies. 我们正在使用csp cookie获取用户信息。

So in below code if User schema could not find useruid i want to send that information to client so user can use in request access form.with below code its throwing 404 when schema don't find useruid. 因此在下面的代码中,如果User架构找不到User ID,我想将该信息发送给客户端,以便用户可以在请求访问表单中使用。下面的代码在架构找不到用户ID时抛出404。 Any idea how to resolve this issue ? 任何想法如何解决这个问题?

user.controller.js user.controller.js

   function handleEntityNotFound(res) {
  return function(entity) {
    if (!entity) {
      res.status(404).end();
      return null;
    }
    return entity;
  };
}

    exports.current = function(req, res) {
      // console.log('username', req);
      User.findById(req.useruid)
          .populate({path: 'groups', select: '_id name', options: {sort: {name: 1}}})
      .execAsync()
    .then(handleEntityNotFound(res))
    .then(responseWithResult(res))
    .catch(handleError(res));
};

If there's no match, findById() returns [] . 如果没有匹配项,则findById()返回[]

Try: 尝试:

 exports.current = function(req, res) {
        User.findById(req.useruid, function (err, results) {
            if (err) { 
                console.log(err);
            }
            if (results.length) {
                responseWithResult(res);
            } else {
                handleEntityNotFound(res);
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM