我開始學習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();
}
);
}
});
});
但它沒有按預期工作,我什麼都收不到。我該如何解決它?
你是什麼意思「它沒有按預期工作」?它輸出了什麼?或者你收到任何錯誤? –
取決於你的數據的外觀,但也許''collection.find({'area.living_room':{$ ne:null}})' – Jenian
我沒有收到任何人。對於那個很抱歉。 – ryan