2017-04-19 85 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