简体   繁体   English

基于登录用户的条件查询

[英]Conditionally Query based on Logged in User

I am currently trying to show products in my database based on which user is logged in. Currently if the user logged in has products (not tied to the user they are their own separate schmea) they can navigate to the products page and see their products. 我目前正在尝试根据登录的用户在数据库中显示产品。当前,如果登录的用户拥有产品(与用户无关,他们是他们自己的独立帐户),则可以导航至产品页面并查看其产品。 What I would like to be able to do is also see products if the user logged in is an admin. 如果用户登录的是管理员,我还想查看产品。 I am currently working with this setup. 我目前正在使用此设置。 I was trying to do it with an $or operator but I felt like that was wrong. 我试图用$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',
                });
            })

What would be the more correct way of doing this? 这样做更正确的方法是什么? I know that this isn't working as is seeing that the userId is pulling back an ObjectId and not a Boolean like isAdmin is set to. 我知道这不起作用,因为看到userId正在拉回ObjectId,而不是将isAdmin设置为布尔值。

What you are actually looking for is not actually done with "query operators" but rather in the construction of the query itself: 您实际上要查找的内容实际上不是使用“查询运算符”完成的,而是在查询本身的构造中完成的:

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
    });

};

Or even "inline" with a ternary operation if that suits you better: 如果更适合您,甚至可以使用三元运算来“内联”

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

This makes sense since you are either passing the query as "empty" {} which means everything when the isAdmin was true OR you are actually sending to match the current userId value ie 这很有意义,因为您要么将query传递为“空” {} ,这意味着isAdmintrue时的所有内容 ,或者您实际上是在发送以匹配当前的userId值,即

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

in cases when there is a specific user you intend to match 如果有特定的用户要匹配

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

相关问题 我想基于Angular中当前登录的用户ID使用firebase作为我的后端进行查询 - I want to make a query based on the current logged in user id in Angular using firebase as my back-end 有条件地显示基于媒体查询的内容 - conditionally display content based on Media Query 插入基于登录用户的文本框值? - Insert textbox value based on logged in user? 根据用户是否登录更改网站上的文本 - change text on website based if user is logged in or not 如何根据登录用户呈现视图? - How to render a view based on the logged in user? 如何根据用户的cookie而不是登录用户限制类似的计数器? - How to limit a like counter based on the cookie of the user instead of logged in user? 根据用户单选输入有条件地显示表单字段 - Show form fields conditionally based on user radio input 如何根据用户 Redux state 有条件地呈现登录或仪表板? - How to conditionally render a Login OR a Dashboard based on a user Redux state? 如何在Mongo中基于集合中的布尔值有条件地查询键 - How to conditionally query keys based on boolean in collection in Mongo 根据URL查询字符串有条件打开弹出视频 - Conditionally open popup video based on URL query string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM