我有这个代表公寓列表的 JSON:
{
"_id": {
"$oid": "5673d1dcf93fe452d80c2c2c"
},
"street": "myStreet",
"buildingNumber": 1,
"apartmentNumber": 1,
"UsersAndQuestions": [
{
"userID": "5673afe4cb62303816bd3d5c",
"questionID": [
"5669d90a058ceddc158e97e2",
"4668d80b158ceggc158e97f2"
]
}
]
}
我想获取某个userID
的questionID
数组。
我正在使用这个http.get
来尝试获取它:
app.get('/api/listing/getQuestionsOfUserInListing/:userid/:listingid', function (req, res) {
var user = req.params.userid;
var listing = req.params.listingid;
Listing.find({
$and: [
{_id: listing},
{'UsersAndQuestions.userID': user}
]
}
, function (err, result) {
res.json(result);
});
});
但我只是取回整个 JSON(正是我在问题开头发布的那个)。
如何获取
"questionID": ["5669d90a058ceddc158e97e2", "4668d80b158ceggc158e97f2"]
?
谢谢!
最佳答案
如上所述here你可以用这样的投影来做到这一点:
Listing.findOne( {_id: listing, 'UsersAndQuestions.userID': user},
{_id: 0, 'UsersAndQuestions.$': 1},
function (err, result) {
res.json(result.UsersAndQuestions[0].questionID);
});
附注另外,我不明白为什么您需要在这里使用 $and 运算符。来自 documentation :
复合查询可以为集合文档中的多个字段指定条件。隐式地,逻辑 AND 连接词连接复合查询的子句,以便查询选择集合中匹配所有条件的文档。
关于javascript - 使用 $http.get 获取嵌套 JSON 中的数组(mongoose 和 nodejs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352611/