[英]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
传递为“空” {}
,这意味着isAdmin
为true
时的所有内容 ,或者您实际上是在发送以匹配当前的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.