0

I'm working on a food blog. I would want to achieve the following structure for the food recipes in my database.

recipes : [
 {mainCategoryRecipe1: {...}},
 {mainCategoryRecipe2: {...}},
 subcategory1: [
   {recipe1: {...}}
 ]
]

I'm posting a form with select field indicating the correct category and subcategory (if needed). I can access these in the Node.js backend.

I can't figure out how to $push in to the database so the data follows the correct structure. I'm using MongoJS. My attempt on this resolves with this structure instead:

recipes : [
 {subcategory1 : recipe1[...]},
 {subcategory1 : recipe2[...]}
]

Here is my code:

db.collection.findAndModify({
        query:{_id: mongojs.ObjectId(userId)},
        update: { $push: {
                recipes : {
                            [recipe.subcategory] : recipe
                          }
            }},
        new: true
    }, function(err, doc, lastErrorObject){
        if(err){
            throw (err)
        } else {
            //console.log(recipe)
            res.render('/success');
        }
    });

Thank you in advance!

Nuuskis
  • 57
  • 3
  • Possible duplicate of [Mongodb $push in nested array](https://stackoverflow.com/questions/27874469/mongodb-push-in-nested-array) – IftekharDani Nov 27 '18 at 12:49

1 Answers1

0

Try with the code belove, If you have any errors please comment them.

db.collection.findOneAndUpdate({
            {_id: new ObjectID(userId)},
            { $push: {
                    recipes : {
                                [recipe.subcategory] : recipe
                              }
                }},
            returnOriginal: false
        }, function(err, doc, lastErrorObject){
            if(err){
                throw (err)
            } else {
                //console.log(recipe)
                res.render('/success');
            }
        });