javascript - 使用 $http.get 获取嵌套 JSON 中的数组(mongoose 和 nodejs)

标签 javascript json node.js mongodb mongoose

我有这个代表公寓列表的 JSON:

{
    "_id": {
        "$oid": "5673d1dcf93fe452d80c2c2c"
    },
    "street": "myStreet",
    "buildingNumber": 1,
    "apartmentNumber": 1,
    "UsersAndQuestions": [
        {
            "userID": "5673afe4cb62303816bd3d5c",
            "questionID": [
                "5669d90a058ceddc158e97e2",
                "4668d80b158ceggc158e97f2"
            ]
        }
    ]
}

我想获取某个userIDquestionID数组。

我正在使用这个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/

相关文章:

javascript - Firebug 扩展 context.sourceCache.load(href) 返回 'Reload the page to get source for: http://'

javascript - 如何最初仅扩展此 d3.js 中选定的 Node ?

json - Postgres JSONB列插入错误: invalid input syntax for type json the input string ended unexpectedly

node.js - 从关系中选择特定字段

javascript - 如何遍历 node.js 中的一系列 promise ?

Javascript DOM,获取节点文本而不丢失间距信息

javascript - 当有人安装扩展程序时,如何将用户电子邮件保存为变量?

python - Robot Framework - 将 JSON 转换为字典

javascript - 在 Node.js 模块中立即调用

javascript - 我如何 'swap' 对我的应用程序中的 react /插件使用react?