从参考模型[重复]中填充所有项目

问题描述 投票:0回答:1

我有一个这样的数据库:

enter image description here

我想从具有x ID的用户那里获取所有列表中的所有listItems。正确的做法是什么?

我正在使用带有猫鼬的节点,并且尝试了以下操作:

await User.findById(user._id).populate('list');

但是意识到我不能从中填充所有ListItem。意思是,我不能这样做:

await User.findById(user._id).populate('list').populate('listItem');

如何从具有x ID的用户那里获得所有列表中的所有listItem?

node.js mongodb mongoose mongoose-populate
1个回答
0
投票

假设UserListListItem是集合,您应该可以使用$lookup来完成此操作。

$lookup


查询:

Here is a live demo of the following query..

数据集:

db.users.aggregate([
  {
    $match: {
      uniqueId: 1
    }
  },
  {
    $lookup: {
      from: "lists",
      localField: "uniqueId",
      foreignField: "userId",
      as: "lists"
    }
  },
  {
    $lookup: {
      from: "listItems",
      localField: "uniqueId",
      foreignField: "userId",
      as: "listItems"
    }
  }
])

结果:

db={ // Simulates a DB  ********
  "users": [ // Simulates a Collection ********
    {
      "firstname": "John",
      "lastname": "Smith",
      "email": "[email protected]",
      "password": "password123",
      "uniqueId": 1
    },
    {
      "firstname": "Jane",
      "lastname": "Doe",
      "email": "[email protected]",
      "password": "123password",
      "uniqueId": 2
    }
  ],
  "lists": [ // Simulates a Collection ********
    {
      "userId": 1,
      "name": "Johns List 1",
      "items": [
        11,
        12,
        13
      ]
    },
    {
      "userId": 2,
      "name": "Groceries",
      "items": [
        21,
        22,
        23
      ]
    }
  ],
  "listItems": [ // Simulates a Collection ********
    {
      "userId": 2,
      "itemId": 21,
      "title": "Apple",
      "notes": []
    },
    {
      "userId": 2,
      "itemId": 22,
      "title": "Banana",
      "notes": []
    },
    {
      "userId": 2,
      "itemId": 23,
      "title": "Strawberry",
      "notes": []
    },
    {
      "userId": 1,
      "itemId": 11,
      "title": "Oil Change",
      "notes": []
    },
    {
      "userId": 1,
      "itemId": 12,
      "title": "Pick Up Grandma",
      "notes": []
    },
    {
      "userId": 1,
      "itemId": 13,
      "title": "Go For Run",
      "notes": []
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.