简体   繁体   中英

How to execute a query in mongoose with params, one of which is an array if the array is undefined?

I need to execute a query with a set of params that are passed through headers. One of the params is an array of strings. The query looks like this:

router.get('/', (req, res) => {
  const { category, subCategory, product, size } = req.headers;
  let sizes,
    params = {};
  if (category) params["category.text"] = category;
  if (subCategory) params["subCategory.text"] = subCategory;
  if (product) params["product.text"] = product;
  if(size) sizes = _.split(size, ',');
  Item.find({
    ...params,
    size: { $in: sizes }
  }).sort({ _id: 1 })
    .then(items => res.json(items.reverse()))
    .catch((err) => res.json({ message: err }));
});

After processing sizes using lodash, it looks like array of strings:

['XL','L']

The problem is that if this parameter size is not passed, then sizes will be undefined. Also I cannot include sizes into params, since they check using mongodb syntax (ie $in ). How to process the query in such a way that it would check the array if it contains values, and ignore it if it was not in the query? I hope I explained it clearly.

I will also give a simplified model to make it clearer:

const mongoose = require('mongoose');

const ItemModel = mongoose.Schema({  
  category: [{
    lang: String,
    text: String
  }],
  subCategory: [{
    lang: String,
    text: String
  }],
  product: [{
    lang: String,
    text: String
  }],
  size: [{
    type: String,
    required: true
  }],  
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Items', ItemModel);

Regards.

You need to simplify your request like this,

router.get('/', (req, res) => {
    let params = {};

    if (req.headers.category) params["category.text"] = req.headers.category;
    if (req.headers.subCategory) params["subCategory.text"] = req.headers.subCategory;
    if (req.headers.product) params["product.text"] = req.headers.product;
    if (req.headers.size) params['size'] = { $in: _.split(req.headers.size, ',') };

    Item.find(params).sort({ _id: 1 })
        .then(items => res.json(items.reverse()))
        .catch((err) => res.json({ message: err }));
});

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