【问题标题】:Nodejs mongoose get results from two collections in one queryNodejs mongoose 在一个查询中从两个集合中获取结果
【发布时间】:2018-10-10 22:16:45
【问题描述】:

所以我遇到了需要使用 mongoose 从 NodeJS 中的两个集合中获取结果的问题。基本上我有users 收藏和boughtItems 收藏。

users 集合由_idusername 组成

boughtItems 集合由item_idusername(购买项目的用户)组成

有人可以展示如何从usersboughtItems 获取结果,所以当我显示所有users 时,他们购买的商品将显示在同一页面中他们的名字旁边。

我有两个模型:UserBoughtItem

User.aggregate([{
    $lookup: {
        from: "boughtitems", // collection name in db
        localField: "username",
        foreignField: "username",
        as: "boughtitems"
    }
}]).exec(function(err, users) {
    console.log(users);
});

此代码块用购买的物品返回用户,但每个购买的物品都是 [Object] 如何从 object 获取完整信息?

所以我做了JSON.stringify(users),现在我得到了所有信息。

我明白了:

enter image description here

如何在渲染文件中显示购买的物品,如下所示:

{{#each users}}
   {{this.boughtitem['item_power']}}
{{/each}}

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您的查询实际上是在获取BoughtItem 数据。问题是console.log,它不打印嵌套对象。如果要打印整个对象,请尝试以下操作:

    console.log(JSON.stringify(users));
    

    【讨论】:

    • 现在如何在文件中显示结果。如果我这样做each,我只能从他们的收藏中查询users 信息。但它不显示来自boughtItems 的任何内容。我在用户数组旁边得到另一个元素数组。
    • 我不确定你的意思。请将代码添加到您的问题中,并显示您的预期结果。
    • 这就是我得到的:{USERS ARRAY OF ELEMENTS},{BUUGHT ITEMS ARRAY OF ELEMENTS}
    • 当我做{{#each users}} 时,我只能从 {USERS ARRAY} 获取信息,如何也从 {bought items array} 获取信息?
    • 我不知道{{#each users}} 是什么意思,也不知道你在哪里使用它进行渲染。请考虑使您的问题中的代码更完整,以向我们展示您如何将 mongoose fetch 与此代码联系起来。
    猜你喜欢
    • 2016-08-08
    • 2021-04-29
    • 2013-10-20
    • 2016-06-18
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多