[英]Mongoose If statement in find query
I am trying to do a find()
but with an if statement. 我试图做一个find()
但带有if语句。
I have the following query: 我有以下查询:
Promise.all([
User.find({ $and: [
{ 'type': 'user' },
{ $or: [
{ username: { $regex: String(value), $options: "i" } },
{ firstName: { $regex: String(value), $options: "i" } },
]}
]})
.then(user => user),
User.countDocuments({ 'type': 'user' })
.then(count => count)
])
.then(promiseData => {
return response.status(200).json({ count: promiseData[1] });
}
So in the promise, the first query finds all the users with the user
type. 因此,在Promise中,第一个查询将查找具有user
类型的所有user
。 What I want to do is, if the user doing the search has a specific permission, change that search. 我想做的是,如果进行搜索的用户具有特定的权限,请更改该搜索。
For instance, let's say an 'admin' user does the search I want to add another query to the search, for instance: 例如,假设一个“管理员”用户执行搜索,我想向该搜索添加另一个查询,例如:
User.find({ $and: [
{ 'type': 'user' },
// If the user is an admin => _if(true){ run this }_
{ 'stuff': true },
// end if
{ $or: [
{ username: { $regex: String(value), $options: "i" } },
{ firstName: { $regex: String(value), $options: "i" } },
]}
]})
.then(user => user),
Is it possible to add another field in my query with an if statement? 是否可以使用if语句在查询中添加另一个字段? I don't want to run 2 queries that are essentially the same thing. 我不想运行2个本质上相同的查询。
You should try group
or facet
pipeline of aggregation to resolve such need. 您应该尝试聚合的group
或facet
管道来解决此类需求。
db.users.aggregate([
{
$facet:{
users: [
{
$match: {
eUserType: 'user',
// query related users
}
}
],
admins:[
{
$match: {
eUserType: 'admin',
// query related admins
}
}
],
}
},
{
// chnage format as per your need.
}
])
onde you got results you concat or merge format your data as per your need. 您可以根据需要获得结果,然后合并或合并数据。
let query = {
$and: [
{ 'type': 'user' },
{ $or: [
{ username: { $regex: String(value), $options: "i" } },
{ firstName: { $regex: String(value), $options: "i" } },
]}
]
}
/// add your logic
if (req.user.admin) {
query['$and'].push({ 'stuff': true });
console.log('req = ', query)
}
/// execute the request
Promise.all([
User.find(query).then(user => user),
User.countDocuments({ 'type': 'user' }).then(count => count)
])
.then(promiseData => {
return response.status(200).json({ count: promiseData[1] });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.