简体   繁体   中英

Mongoose dynamic query in find with $in is not working

I am using Node.js and Mongoose 5+ to dynamically build a query in the database. The variable filterField is the field name and filterValues is an array. So, my code is like this:

if (req.currentUser.activePage) {
    queryParam['pageId'] = req.currentUser.activePage;
    if (filterField && filterValues)
        queryParam[filterField] = { $in: filterValues };
    query = Model.find(queryParam);
    console.info(queryParam);
}
Model.paginate(query, options, async (err, result) => {
    if (err) {
        res.status(500).json({ message: err.errmsg });
    } else {
        res.status(200).json(result.docs);
    }
});

The printed queryParam is as follow:

{ pageId: '123', id: { '$in': [ 1, 2 ] } }

If I run this query directly in the Mongo shell it works fine.

However, when I run this query in Mongoose, it does not return anything when the id: {$in .. is present.

What is the error?

you have passed wrong parameter query to Model.paginate() method ,try this way :

if (req.currentUser.activePage) {
    queryParam['pageId'] = req.currentUser.activePage;
    if (filterField && filterValues){ 
        queryParam[filterField] = { '$in': filterValues };
    }
    Model.paginate(queryParam, options, async (err, result) => {
      if (err) {
        res.status(500).json({ message: err.errmsg });
       } else {
        res.status(200).json(result.docs);
       }
    });
}

I figured out the error, it is caused by the mongoose-paginate plugin. So, if you are using this plugin with Mongoose, be careful with the parameters you pass to the query.

In my case, passing an array as filter with the option $in does not work with mongoose-paginate .

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