首页 > 解决方案 > 检索验证用户的订单

问题描述

  1. 获取方法
  2. 使用accessToken经过身份验证的用户。
  3. 只有非管理员帐户才能继续。
  4. 用户应该只能检索他的订单。

路由器

router.get("/my-orders", auth.verify, (req, res) => {

    const user = auth.decode(req.headers.authorization);

    if (!user.isAdmin) {

        UserController.getMyOrders(req.body).then(getMine => res.send(getMine));


    } else {

        return res.status(403).send("Access denied.");
    }

});```

控制器

module.exports.getMyOrders = (body) => {

    return User.find({}, {
        "isAdmin": 0,
        "_id": 0,
        "password": 0
    });
}

我得到了一切。有人可以帮我编写代码如何过滤令牌所属的用户并检索他的订单并且无法获取其他用户的订单吗?

标签: javascriptobjectmongoose

解决方案


通过在您的方法中传递一个空对象.find,您是在告诉 mongodb 查找所有内容。我假设body您有一些数据可以找到特定用户,如果是这样,您会使用它。例如。如果body包含用户名,你会写...

module.exports.getMyOrders = (body) => {
    return User.find({username: body.username});
}

这是有关 db.collection.find() 的更多信息

编辑 - 通过 JWT 查找用户:

router.get("/my-orders", auth.verify, (req, res) => {
    //Here you have decoded your JWT and saved it as user
    const user = auth.decode(req.headers.authorization);

    if (!user.isAdmin) {
        //here you are passing user instead of req.body
        UserController.getMyOrders(user).then(getMine => res.send(getMine));


    } else {

        return res.status(403).send("Access denied.");
    }

});

module.exports.getMyOrders = (user) => {
    //now you are using 'username' from the decoded jwt to look up the user
    return User.find({username: user.username});
}

推荐阅读