0

Here is what my current collection looks like:

Object: foods,
Group: {
    Name: fruit
    Kinds: {
       Name: Apple,
       Details: 
           {
           Name: Honey Crisp,
           Color: red,
           Taste: sweet
           }
       
    }
    Name: Meat
    Kinds: {
       Name: Pork,
       Details: 
           {
           Name: Pork Chop,
           Color: red,
           Taste: sweet
           }
           {
           Name: Bacon,
           Color: red,
           Taste: salty
           }
       
    }
}

So I'd like to add another type of apple into the details document. I've seen people add documents one layer deep with $push, but I have not seen any tutorials on how to add a document more than one layer deep. Please help.

EDIT I'd like to add this under the details of apple without using indexes.

          {
           Name: Red Delicious,
           Color: red,
           Taste: Sweet
           }
LUKER
  • 540
  • 1
  • 5
  • 23

1 Answers1

1

This is wrong on so many levels, please next time use [] for arrays, use , between fields.

Answer for your question is arrayFilters . With them you can you do magic, you are looking for.

  • This worked, but it does not generate an id when pushed. Would you be able to help me out with that? – LUKER Jul 04 '20 at 04:23
  • It will never generate id, that's second thing i would suggest you -> generate id on every layer of your array, if you want work with it. If it's just simple array, you don't have to, but if you working with objects you should generate id. Like you have group so id should be either 'id' or for better understanding "groupId". You can use ObjectId()[https://docs.mongodb.com/manual/reference/method/ObjectId/] function for generating ids. Iam not sure how it works with mongoose, iam using native mongo driver tho. – Martin Hoang Jul 06 '20 at 04:02
  • 1
    This should help you `var mongoose = require('mongoose');` `var id = mongoose.Types.ObjectId();` I got it from this [https://stackoverflow.com/questions/17899750/how-can-i-generate-an-objectid-with-mongoose] post. – Martin Hoang Jul 06 '20 at 04:03