我开始学习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