简体   繁体   中英

Mongoose If statement in find query

I am trying to do a find() but with an if statement.

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. 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? I don't want to run 2 queries that are essentially the same thing.

You should try group or facet pipeline of aggregation to resolve such need.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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