【问题标题】:How to get mongoose schema result properly with missing field in JSON如何在 JSON 中缺少字段的情况下正确获取猫鼬模式结果
【发布时间】:2021-10-27 00:49:40
【问题描述】:

我是 Node.js 和猫鼬的新手。我尝试了很多东西,但无法得到我想要的结果。

谁能帮助谁知道如何解决这个问题,谁曾经遇到过这个问题或知道这个问题的解决方案?

下面是我的数据库屏幕,其中有 3 条记录如下所示。

我已经编写了这段代码,它返回的结果如下所示:

router.get("/categoryFields", async (request, response) => {
    const categories = await categoryModel.find({}).select("parentId title slug");
    try {
      response.send(categories);
    } catch (error) {
      response.status(500).send(error);
    }
  });

JSON 结果 =>

[
    {
        "_id": "61779e5c1e4ed11e96301ccd",
        "title": "Clothing",
        "slug": "hello"
    },
    {
        "_id": "61779e8d1e4ed11e96301ccf",
        "parentId": "61779e5c1e4ed11e96301ccd",
        "title": "Shoe",
        "slug": ""
    },
    {
        "_id": "6177c1cd6d3e170ae58c89c3",
        "title": "Electric",
        "slug": ""
    }
]

但我需要得到这样的结果 - 我希望每个对象都有parentID

[
    {
        "_id": "61779e5c1e4ed11e96301ccd",
        "parentId": "",
        "title": "Clothing",
        "slug": "hello"
    },
    {
        "_id": "61779e8d1e4ed11e96301ccf",
        "parentId": "61779e5c1e4ed11e96301ccd",
        "title": "Shoe",
        "slug": ""
    },
    {
        "_id": "6177c1cd6d3e170ae58c89c3",
        "parentId": "",
        "title": "Electric",
        "slug": ""
    }
]

请谁能帮我在猫鼬中做到这一点?

【问题讨论】:

  • 我可以看看你的架构吗?

标签: node.js mongodb express mongoose


【解决方案1】:
db.collection.find({},
{
  "parentId": {
    $cond: {
      if: "$parentId",
      then: "$parentId",
      else: ""
    }
  },
  "title": 1,
  "slug": 1
})

Test Here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 2020-08-25
    • 2019-05-23
    • 2021-08-21
    • 2018-08-23
    • 2021-06-20
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多