猫鼬查找和查找

时间:2020-05-26 15:29:54

标签: javascript mongodb mongoose

我在一家公司中想要列出团队的用户故事。 我有两张桌子。 一个包含美国。 另一个包含Sprint,而Sprint本身包含在此Sprint期间创建的美国ID。

Shemas看起来像这样。


const Userstories = mongoose.Schema({
    Name: String,  
    Date: Date
});

const Sprint= mongoose.Schema({
    Name: String,
    Userstories: [{type: mongoose.Schema.Types.ObjectId, ref: "userStory"}],
    Author: String,
    Date: Date
});

有时我需要特定Sprint的美国列表。

为此,我使用了查找功能。 但是我不知道为什么,我无法同时进行查找。 最后,我做到了:

Sprint.aggregate([{
        $lookup: {
            from: 'userstories',
            localField: 'Userstories',
            foreignField: '_id',
            as: 'Userstories'
        }
    }
const photos = agregate.find(us => us._id == id);

我先进行汇总,然后再进行查找。

但是我想用这种方法会花费很多计算时间。

那我为什么想知道Mongoose是否优化了这种情况? 如果没有,该如何更正确地编写请求?

1 个答案:

答案 0 :(得分:1)

您需要使用$match聚合来查找Sprint。

因此您可以使用以下示例获取路线:

router.get("/sprints/:id", async (req, res) => {
  const id = req.params.id;

  const result = await Sprint.aggregate([
    {
      $match: {
        _id: ObjectId(id),
      },
    },
    {
      $lookup: {
        from: "userstories",
        localField: "Userstories",
        foreignField: "_id",
        as: "Userstories",
      },
    },
  ]);
  res.send(result);
});

假设您有以下两个Usertories文档:

{
    "_id" : ObjectId("5ecd60f21f3c84289488d6d9"),
    "Name" : "story 1",
    "Date" : ISODate("2020-05-26T21:33:22.543+03:00")
},
{
    "_id" : ObjectId("5ecd60fb1f3c84289488d6da"),
    "Name" : "story 2",
    "Date" : ISODate("2020-05-26T21:33:31.692+03:00")
},

此冲刺文档:

{
    "_id" : ObjectId("5ecd610f1f3c84289488d6db"),
    "Userstories" : [
        ObjectId("5ecd60f21f3c84289488d6d9"),
        ObjectId("5ecd60fb1f3c84289488d6da")
    ],
    "Name" : "Sprint 1",
    "Author" : "Author 1",
    "Date" : ISODate("2020-05-26T21:33:51.928+03:00")
}

此冲刺的结果将是这样的:

[
    {
        "_id": "5ecd610f1f3c84289488d6db",
        "Userstories": [
            {
                "_id": "5ecd60f21f3c84289488d6d9",
                "Name": "story 1",
                "Date": "2020-05-26T18:33:22.543Z",
                "__v": 0
            },
            {
                "_id": "5ecd60fb1f3c84289488d6da",
                "Name": "story 2",
                "Date": "2020-05-26T18:33:31.692Z",
                "__v": 0
            }
        ],
        "Name": "Sprint 1",
        "Author": "Author 1",
        "Date": "2020-05-26T18:33:51.928Z",
        "__v": 0
    }
]