简体   繁体   English

如何使用 Mongoose/MongoDB 获取 mongoose 查询以仅返回文档内的特定字段?

[英]How to get a mongoose query to return only specific field inside of a document using Mongoose/ MongoDB?

I'm trying to code a menu manager where I can update delete and create both new menu items and categories.我正在尝试编写一个菜单管理器,我可以在其中更新删除和创建新的菜单项和类别。 I need to get a query to return only the menu-items not all of the other category data inside of the document.我需要查询以仅返回菜单项而不是文档内的所有其他类别数据。

How can I do that?我怎样才能做到这一点?

This is the schema:这是架构:

{
   Categories:
     name: ffjs,
     id: fhsjd,
     menu_items: [
       item1: {
         name: fhrse,
         ingredients: [jksf,sjdfk,fjd]
       }, ...
    ]
}

I would like the query to just return item1, item2, item3 and so on, but can't get the query to work.我希望查询只返回 item1、item2、item3 等等,但无法使查询正常工作。

I have tried:我试过了:

Categories.find({"items" : $all})
Categories.find({}).select("items")

I've also tried querying for specific items just to test and only ever returns the full document such as:我也试过查询特定项目只是为了测试并且只返回完整的文档,例如:

Categories.find({"items.name" : "ramen"})
Categories.find({items :{"$elemMatch" : {name: "ramen"}}}, {"items.name" :1})

Solution 1: You can use aggregate method to achieve it, check below:解决方案一:可以使用聚合的方式来实现,检查如下:

Categories.aggregate([
    { $match: { $and: [{id: "fhsjd" }, { "items.name" : "ramen" } ] } },
    { $project: { _id: 0, menu_items: 1 } }
  ])

Here you can $match for query and $project for filter (0: to exclude and 1 to include)在这里,您可以使用 $match 进行查询,使用 $project 进行筛选(0:排除,1 包括)

Solution 2: To return specific record, use below:解决方案 2:要返回特定记录,请使用以下方法:

Categories.find({ "items.name" : "ramen" }, { items: 1, _id: 0 })

To return all items, use below:要退回所有项目,请使用以下内容:

Categories.find({}, { items: 1, _id: 0 })

Hope one of the solution works for you.希望其中一种解决方案适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM