根据数据库数组中项目的值,Mongoose选择结果

问题描述:

我有一个模式字段(价格),它是一个数组,通常只有1个价格,但有时销售价格列为数组中的第二个项目。根据数据库数组中项目的值,Mongoose选择结果

我希望能够查询此字段并返回所有产品,从最低到最高排序(而我在它的时候,使用$ gt和$ lt来按范围进行选择)。

但我的挑战是处理销售价格,这是我阵列中的第二个价值。我需要能够按这个价格排序,而不是第一个价格,如果实际上有售价。我不知道怎么说:“如果(价格[1]){使用权价格[1]}在我的猫鼬查询。

UPDATE

我能够得到几乎我想用什么下面的查询
我的问题是,当我把price.1首先是假的位置(这些部分是用$和划分的)我只得到反映产品 price.1的结果当我把第二个首先,是那个价格.1是真的,我只得到相反的产品,没有价格1.

是猫鼬只读我的查询的第二部分?

Product.find({ $and: 
    [{"price.1": {$exists : false }}, 
    {"price.0": {$gte : req.body.lower_price}}, 
    {"price.0": {$lte : req.body.higher_price} }], 
    $and : [{"price.1": {$exists: true}}, 
    {"price.1": {$gte : req.body.lower_price}}, 
    {"price.1": {$lte : req.body.higher_price} }]}) 
.exec(function(err, products){ 
    if(err){ 
     console.log(err) 
    } 
    else{ 
     res.send(products) 
    } 
}); 
+0

你能提供一个测试用例的一些样本文档上述问题,即,你有什么期望输出给定的查询? – chridam

Model.find({$or :[{"price.1": {$exists: false}}, {"price.1": {$gt : 10}}]}) //get all documents where either second element of the price array doesn't exist OR if it does it's greater than 10 
    .sort("price.1") // asc. Docs without second element will come first. Use -price for desc 
    .exec(function(err, res){ 
     if(err){ 
      console.log(err) 
     } 
     else{ 
      console.log(res) 
     } 
    });