我希望下面的代码片段使我的问题更加清楚。我可以获取一个嵌入了类别对象数组的对象。从类别对象,我只想显示某些属性。
所以这就是我现在得到的:
{
"photo": [],
"_id": "5ec55ae39eere8ert85bf8fe749",
"title": "Blog about coding",
"description": "Hi, I want to share with you my incredible journey as a software developer...",
"rate": 3,
"category": [
{
"_id": "5ec55ae39aaa78985f8fe74a",
"name": "programming",
"display_name": "Programming"
}
],
"createdAt": "2020-05-20T16:29:23.982Z",
"updatedAt": "2020-05-20T16:29:23.982Z",
"__v": 0
}
使用以下代码:
/* GET blog with id */
router.get("/:id", async (req, res, next) => {
try {
const blog = await Blog.findById(req.params.id); // How to filter out fields of objects in category array?
res.send(blog);
} catch(ex) {
res.status(400).send(ex);
}
});
这就是我真正想要的:
{
"photo": [],
"_id": "5ec55ae39eere8ert85bf8fe749",
"title": "Blog about coding",
"description": "Hi, I want to share with you my incredible journey as a software developer...",
"rate": 3,
"category": [
{
"display_name": "Programming"
}
],
"createdAt": "2020-05-20T16:29:23.982Z",
"updatedAt": "2020-05-20T16:29:23.982Z",
"__v": 0
}
因此,在类别中,我只需要“ display_name”
我怎么能得到这个。我以为以前看过解决方案,但现在找不到了。
由于您使用的.findById()
是猫鼬包装器,.findOne({_id: ObjectId()})
因此减轻了将输入字符串转换为的负担ObjectId()
,但是.find()
对投影没有太多帮助,因此您需要列出所有字段,如下所示:
/** .findById(inputString, projection) */
Blog.findById(req.params.id,
{
"category.display_name": 1,
"title": 1,
"description": 1,
"rate": 1,
"createdAt": 1,
"updatedAt": 1
})
/** Or */
Blog.findById(req.params.id,
{
"category._id": 0,
"category.name": 0,
})
测试:由于游乐场不能使用以下.findById
测试.find()
:mongoplayground
但是,如果您倾向于使用聚合,则可以在投影中做更多的事情:
const mongoose = require('mongoose');
/* GET blog with id */
router.get("/:id", async (req, res, next) => {
try {
const blog = await Blog.aggregate([{$match : {_id : mongoose.Types.ObjectId(req.params.id)}},
{ $addFields: { category: { $map: { input: "$category", in: { display_name: "$$this.display_name" } } } } }
]);
res.send(blog);
} catch(ex) {
res.status(400).send(ex);
}
});
测试: mongoplayground
注意:此聚合查询将遍历category
数组并仅保留display_name
在每个对象中。仅在需要排除category
对象中的许多字段时才使用此管道。我建议使用第二个选项,.findById()
因为您无需转换string
为ObjectId()
聚合管道,而只需要排除类别数组的字段name
和_id
内部对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句