Moongose:按mathsorting,在string数组中search多个值

你好同胞SO用户,

我遇到了一些先进的mongoose查询,我根本无法从文档中找出答案。

首先,我想按一些math来sorting。 基本上我想能够通过两个对象的价格差异进行sorting。 我有“价格”和“旧价格”,其中包含基本的数字值。 然后,我想减去他们,并以最高的折扣sorting。 所以在SQL中,我会是这样的

ORDER BY (oldprice - price) 

我遇到的另一个问题是通过string数组筛选string数组。

所以基本上我有一个“裤子”模型,与一个[大小]对象(string数组),其中包含多个尺寸。 现在我想能够search多个用户select的大小的分贝,并find所有的裤子,其中包含一个选定的大小。

我试过了:

 Pants.find({ name: new RegExp(search, 'ig'), sizes: { $in: [selectedSizes] } }).skip(skip).limit(limit).sort(sort).execFind(function(err, pants) { return res.send(pants); }); 

如果一个值位于“selectedSizes”中,哪个工作正常,但失败并具有多个值。

希望有人有一些想法;-)


裤子型号:

 var PantsSchema; PantsSchema = new mongoose.Schema({ supplier: { type: String }, manufacturer: { type: String }, web: { type: String }, name: { type: String }, link: { type: String, required: true, unique: true }, image: { type: String }, sizes: { type: [String] }, price: { type: Number }, oldprice: { type: Number }, added: { type: Date, "default": Date.now }, updated: { type: Date } }); 

对于按问题排列的顺序,您需要在Mongo中创build一个存储oldPrice - price的值的oldPrice - price因为您只能按字段进行sorting(并且您需要为此字段编制索引)。

那么你只需要在你的mongoose调用中添加一个sortexpression式:

 .sort('priceDifference', 1); // 1 or -1 depending on ascending or descending 

对于第二个问题,您需要创build$orexpression式,其中每个expression式对应于您要查找的大小。 我认为这看起来像这样:

 .find( { $or : [ { sizes : { $in: ['m'] } }, { sizes : {$in: ['l'] } } ] } )