0

mongoose scheme:

var restsSchema = new Schema({
    name: String,
    menu: mongoose.Schema.Types.Mixed
});

simplfied document:

{
    name: "Dominos Pizza",
    menu:{
         "1":{
              id: 1,
              name: "Plain Pizza",
              soldCounter: 0
           },
         "2":{
              id: 2,
              name: "Pizza with vegetables",
              soldCounter: 0
            }
     }
}

I'm trying to update the soldCounter when given a single/array of "menu items" (such as "1" or "2" objects in the above document) as followed:

function(course, rest){
    rest.markModified("menu.1");
    db.model('rests').update({_id: rest._id},{$inc:  {"menu.1.soldCounter":1}});
}

once this will work i obviously will want to make it more generic, something like: (this syntax is not working but demonstrate my needs)

function(course, rest){
    rest.markModified("menu." + course.id);
    db.model('rests').update({_id: rest._id},{$inc:{"menu.+"course.id"+.soldCounter":1}});
}

any one can help with this one?

I looked for an answer but couldn't find nothing regarding the 3rd level.

UPDATE: Added id to the ducument's subDocument

TBE
  • 1,002
  • 1
  • 11
  • 32

1 Answers1

1

I think you want add all ids into sub-document, one way you can do as following.

Rest.find({_id: rest._id}, function(err, o) {
    // add all ids into sub-document...
    Object.keys(o.menu).forEach(function(key) { 
        o.menu[key].id = key; 
    });

    o.save(function(err){ ... });
});

It seems you want to operate the key in query, I am afraid you cannot do it in this way.

Please refer to the following questions.

Mongodb - regex match of keys for subobjects

MongoDB Query Help - query on values of any key in a sub-object

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214
  • I'm sorry for the late update, i just realised that i have the key in the document as well, please see my updates document. What i mean is that i do not need to query by keys of subobjects. – TBE Jan 25 '16 at 14:26
  • hey, i have posted a new question to make it more clear of what i need: http://stackoverflow.com/questions/35009941/mongoose-efficient-update-on-an-indexed-array-of-mongoose-schema-types-mixed – TBE Jan 26 '16 at 08:51