Perry Craft
Perry Craft

Reputation: 309

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.

    // 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.

Upvotes: 0

Views: 57

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

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 i.e

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

in cases when there is a specific user you intend to match

Upvotes: 1

Related Questions