2017-04-19 62 views
0

我開始學習NodeJS和MongoDB。我想檢索MongoDB的數據,但遇到了問題:在mongodb中查詢數據

數據:

{ 
"_id": ObjectId("58f6e6e09f800932f0285ea7"), 
"id_user": "1", 
"username": "admin", 
"password": "123", 
"area": { 
    "livingroom": { 
     "id_room" : "001", 
     "devices" : [ 
      { 
       "id_device" : "1", 
       "device_name" : "Light 1", 
       "status" : "0", 
       "read-only" : "0" 
      }, 
      { 
       "id_device" : "2", 
       "device_name" : "Light 2", 
       "status" : "0", 
       "read-only" : "1" 
      } 
     ] 
    }, 

    "garage": { 
     "id_room" : "002", 
     "devices" : [ 
      { 
       "id_device" : "1", 
       "device_name" : "Light 1", 
       "status" : "0", 
       "read-only" : "0" 
      }, 
      { 
       "id_device" : "2", 
       "device_name" : "Light 2", 
       "status" : "0", 
       "read-only" : "0" 
      } 
     ] 
    }, 
} 

}

現在,我只想只能通過使用的NodeJS檢索 「客廳」 的數據:

app.get('/devices', function (req, res) { 
mongodb.connect(url, function (err, db) { 
    if (err) { 
     console.log('Unable to connect to the mongoDB server. Error:', err); 
    } else { 
     console.log('Connection established to', url); 
     var collection = db.collection('Home'); 
     collection.find({'area': 'livingroom'}).toArray(

      function (err, result) { 
       if (err) { 
        console.log(err); 
       } else if (result.length) { 
        res.send(result); 

       } else { 
        console.log('No document(s) found with defined "find" criteria!'); 
       } 
       db.close(); 
      } 
     ); 
    } 
}); 

});

但它沒有按預期工作,我什麼都收不到。我該如何解決它?

+0

你是什麼意思「它沒有按預期工作」?它輸出了什麼?或者你收到任何錯誤? –

+0

取決於你的數據的外觀,但也許''collection.find({'area.living_room':{$ ne:null}})' – Jenian

+0

我沒有收到任何人。對於那個很抱歉。 – ryan

回答

0

,如果你只希望living_room子文檔 - 你可以做collection.find({'area.living_room': {$ne: null}}, {'area.living_room':1})

這樣你就可以得到文檔{area:{living_room:{...}}

read more關於投影嵌入式文檔。

0

如果要檢索livingroomid_room:"001"您需要修改查找查詢是這樣的:

 var collection = db.collection('Home'); 
     collection.find({'area.livingroom.id_room':"001"},function(err,data){ 
      if(err){ 
      console.log(err); 
      }else{ 
      console.log(data); 
      } 
     db.close(); 
    }) 

如果要通過裝置在livingroomid_device:"1"檢索,你需要修改查找查詢是這樣的:

collection.find({'area.livingroom.devices.id_device':"1"},function(err,data){....}); 
+0

不幸的是,它記錄錯誤的傢伙。 可讀{ pool:null, ..... – ryan