【问题标题】:Moongose: sort by math and search by multiple values in string arrayMongoose:按数学排序并按字符串数组中的多个值搜索
【发布时间】:2012-10-03 17:04:10
【问题描述】:

各位 SO 用户,您好,

我遇到了一些高级 Mongoose 查询,我根本无法从文档中弄清楚。

首先,我想按一些数学排序。 基本上我希望能够按两个对象的价格差异进行排序。 我有“价格”和“旧价格”,其中包含基本数值。 然后我想减去它们并按最高折扣排序。 所以在 SQL 中我会像

ORDER BY (oldprice - price)

我遇到的另一个问题是通过字符串数组过滤字符串数组。

所以基本上我有一个“裤子”模型,带有一个 [size] 对象(字符串数组),其中包含多种尺寸。 现在我希望能够通过多个用户选择的尺码搜索数据库,并找到包含 ONE 所选尺码的 ALL 裤子。

我已经尝试过:

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    对于按问题排序,您需要在Mongo 中创建一个存储oldPrice - price 值的字段,因为您只能按字段排序(并且您需要索引该字段)。

    然后你只需在你的mongoose 调用中添加一个sort 表达式:

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

    对于第二个问题,您需要创建$or 表达式,每个大小对应一个您正在寻找的。我认为它看起来像这样:

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

    【讨论】:

    • 感谢您的回答 ;-) 当我有机会测试它时,我将您的答案设置为“已解决”!
    猜你喜欢
    • 2011-12-19
    • 2019-03-22
    • 2022-11-24
    • 1970-01-01
    • 2022-01-27
    • 2022-12-12
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多