简体   繁体   中英

Only use $in operator if a certain condition is met - Mongoose

Okay so this is probably just me being stupid and not having looked through the MongoDB docs properly but anyway here's the deal :

I have a RESTful API route which looks like this:

GET /api/users?ids[]=id1&ids[]=id2

Which gets parsed into an object that looks like this:

var parsedObject = {ids: ['id1', 'id2']}

This returns the users with the specified ids from the query string. Now, I want this to be optional so a request like this could also be valid:

GET /api/users

In mongoose, in order to find the users with the specified ids (if any), I need to use the $in operator when querying as follows:

UserSchema.find()
  .where('_id').in(req.query.ids)
  .exec(function(err, users){
    //some code
  });

However, when req.query.ids doesn't exist, instead of returning all documents, it returns nothing.

I have already tried stuff like this:

var queryIds = req.query.ids || {};

How can I use $in only if req.query.ids exists? Surely there must be a better way than doing something like this:

if (req.query.ids) {
  UserSchema.find()
    .where('_id').in(req.query.ids)
    .exec(function(err, users){
      //some code
    });
} else {
  UserSchema.find()
    .exec(function(err, users){
      //some code
    });
}

I hope this makes sense... Thanks for your time!

Maybe instead of:

var queryIds = req.query.ids || {};

try this:

var queryIds = req.query.ids || [];

because it should be an array and not an object.

But most likely you will have to do a conditional query, maybe something like this:

UserSchema.find(req.query.ids ? {_id: {$in: req.query.ids}} : {})
    .exec(function(err, users){
      //some code
    });
}

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