我两天都很沮丧,因为我是nodeJS和JSon的新手。 我的英文不好,我有一个在子数据中搜索数据的案例,并将结果放在浏览器中。 这是我的代码:
var doc = [{
"name": "yadi",
"hobby": [{
"home": "watch news",
"bed_room": "read comics"
}, {
"home": "watch ufc",
"bed_room": "eat candy"
}]
},
"name": "dony",
"hobby": [{
"home": "sleep",
"bed_room": "eat dog food"
}, {
"home": "watch disney",
"bed_room": "breathing"
}]
}];
var db = new Nedb();db.insert(doc, function(err, newDoc) {
console.log(JSON.stringify(newDoc, null, ' '));
//search data
db.find({
"name": "yadi"
}, {
"hobby": {
$elemMatch: {
"home": "watch news"
}
}
}, function(err, docs) {
console.log ("RESULT "+JSON.stringify(docs, null, ' '));
})
})
我如何使用此结果获取数据?
"hobby": [{
"home": "watch news",
"bed_room": "read comics"
}]
答案 0 :(得分:0)
以下内容应该有效。除了这里和那里的一些括号以及投影中的"_id": 0
之外,你基本上没有错过很多。
var doc = [{
"name": "yadi",
"hobby": [{
"home": "watch news",
"bed_room": "read comics"
}, {
"home": "watch ufc",
"bed_room": "eat candy"
}]
}, {
"name": "dony",
"hobby": [{
"home": "sleep",
"bed_room": "eat dog food"
}, {
"home": "watch disney",
"bed_room": "breathing"
}]
}];
var db = new Nedb();
db.insert(doc, function(err, newDoc) {
console.log(JSON.stringify(newDoc, null, ' '));
});
//search data
db.find({
"name": "yadi"
}, {
"_id": 0, // exclude _id
"hobby": {
$elemMatch: {
"home": "watch news"
}
}
}, function(err, docs) {
console.log ("RESULT "+JSON.stringify(docs, null, ' '));
});