Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

node.js - 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.

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})
question from:https://stackoverflow.com/questions/65923886/how-to-get-a-mongoose-query-to-return-only-specific-field-inside-of-a-document-u

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

Solution 2: To return specific record, use below:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...