我是 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": ""
}
]
請任何人都可以幫助我如何在貓鼬中做到這一點?
uj5u.com熱心網友回復:
db.collection.find({},
{
"parentId": {
$cond: {
if: "$parentId",
then: "$parentId",
else: ""
}
},
"title": 1,
"slug": 1
})
在這里測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338562.html
上一篇:類別和子類別架構設計
