组中mongo对象的属性?"/>
如何删除数组中mongo对象的属性?
我希望下面的摘录使我的问题更加清楚。我可以获取一个嵌入了类别对象数组的对象。我只想从类别对象中显示某些属性。
所以这就是我现在得到的:
{
"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,
})
Test:由于操场无法使用.findById
,请使用.find()
进行测试:mongoplayground
但是如果您倾向于使用aggregation,则可以在投影中做更多的事情:
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);
}
});
Test: mongoplayground
注:此聚合查询遍历category
数组,并且在每个对象中仅保留display_name
。仅当需要在category
对象中排除很多字段时,才使用此管道。我建议在.findById()
中使用第二个选项,因为您无需将string
转换为ObjectId()
和聚合管道就可以排除类别数组对象内的字段name
和_id
。
更多推荐
如何删除数组中mongo对象的属性?
发布评论