2016-10-17 30 views
1

我有一個模式字段(價格),它是一個數組,通常只有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

回答

1
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) 
     } 
    }); 
相關問題