繁体   English   中英

基于登录用户的条件查询

[英]Conditionally Query based on Logged in User

我目前正在尝试根据登录的用户在数据库中显示产品。当前,如果登录的用户拥有产品(与用户无关,他们是他们自己的独立帐户),则可以导航至产品页面并查看其产品。 如果用户登录的是管理员,我还想查看产品。 我目前正在使用此设置。 我试图用$or运算符来做,但是我觉得那是错误的。

    // Get all products for the admin page if the user is logged in
    exports.getProducts = (req, res, next) => {
        //Product.find({userId: req.user._id}) <-- this works for finding  products that the user logged in created
          Product.find({$or: [{userId: req.user._id}, {userId: req.user.isAdmin}]) <-- This is my attempt to get products as admin
            .then(products => {
                res.render('admin/products', {
                    // Create a variable called prods that will store all products from the found products in the DB
                    prods: products,
                    pageTitle: 'Admin Products',
                    path: '/admin/products',
                });
            })

这样做更正确的方法是什么? 我知道这不起作用,因为看到userId正在拉回ObjectId,而不是将isAdmin设置为布尔值。

您实际上要查找的内容实际上不是使用“查询运算符”完成的,而是在查询本身的构造中完成的:

exports.getProducts = (req, res, next) => {
  let query = {};                 // Default as a empty object
  if ( !req.user.isAdmin ) {      // Only add criteria when NOT admin
    query.userId = req.user._id;
  }

  // Then run the query
  Product.find(query)
    .then(prods => res.render({
      prods, pageTitle: 'Admin Products', path: '/admin/products'
    }))
    .catch(err => {
      // handle any errors, probably passed to next
    });

};

如果更适合您,甚至可以使用三元运算来“内联”

Product.find((req.user.isAdmin) ? {} : { userId: req.user._id })

这很有意义,因为您要么将query传递为“空” {} ,这意味着isAdmintrue时的所有内容 ,或者您实际上是在发送以匹配当前的userId值,即

find({ userId: ObjectId("54759eb3c090d83494e2d804") })

如果有特定的用户要匹配

暂无
暂无

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

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