0

Firstly, here is my document:

{
"_id" : "Members",
"Member_Index" : [ 
    "wCwam8zqotSSMeyDwOfEfmMhZFn2", 
    "wpbcaIFEMeds3HmM2JOmIz05RGq1", 
    "imbb0r1aOhMzFnHCDWKBiLhSTr03", 
    "mzle6EjxNHVIrySiVo90ftyK2jC3", 
    "j8xP1GzeEIRM0Oq07g7b1vgSpPv1"
],
"Classes" : [ 
    {
        "date" : ISODate("2017-08-30T05:00:21.437Z"),
        "className" : "Run",
        "_id" : "1504069221437",
        "registeredMembers" : []
    }
]}

I am trying to push (append) a string into the Classes.ARRAY_INDEX.registeredMembers array. I am able to update the index 0 with this:

gym.findByIdAndUpdate("Members", 
                                    {$push: {'Classes.0.registeredMembers': req.query.UID}},
                                     {safe: true, upsert: true}, function(err, model) {
                                    if (model != null) {
                                        console.log('Updated with UID');
                                        res.sendStatus(200);
                                    } else {
                                        console.log('Failed to update');
                                        console.log(err);
                                        res.status(404).send('Failed to update')
                                    }
                                });

I would like to change the index (which I know from another query). I tried passing in a concatenated string in the field parameter; however, it expects an object.

var param = 'Classes.' + index + '.registeredMembers';

Passing in the above variable in place of 'Classes.0.registeredMembers' results in the following error:

Error: Invalid atomic update value for $push.

Any tips/pointers would be greatly appreciated! Please let me know if you need more info.

Here is the full function:

router.get('/register_class', function(req, res, next) {

if (!req.query.token || !req.query.UID || !req.query.GID || !req.query.EID) {
    console.log('Invalid Params');
    res.status(404).send('Invalid Parameters');
    return null;
}

checkAuth(req.query.token, function(authed){
    if (!authed) {                
        console.log('Invalid token passed. Permission Denied');
        res.send('Unauthorized');
        return;
    }
});

console.log('Valid Access');


gid.findOne( {'GID': req.query.GID}).exec(function(err, GID) {
    if (err) {
        return res.send("Error");
    } else {
        if (GID == null) {
            res.status(404).send('Invalid GID');
        } else {
            var GCOL = GID.GCOL;
            var gym = require('../models/gym.js')(GCOL, randomstring.generate(32));

            if (!gym) {
                console.log('Invalid Collection Name');
                res.status(404).send('Invalid Parameters')
                return null;
            }

            console.log('Valid Collection');



            gym.findOne( {'_id': "Members"}).exec(function(err, UID) {
                if (err) {
                    return res.send(err);
                } else {
                    if (UID == null) {
                        res.status(404).send('Invalid UID');
                    } else {
                        var classesArray = UID.Classes;

                        for (i = 0; i < classesArray.length; i++) { 
                            if (classesArray[i]._id == req.query.EID) {
                                var where = ["Classes." + i + ".registeredMembers"];
                                console.log('Where: ' + where);


                                var queryParam = {where : req.query.UID};


                                gym.findByIdAndUpdate("Members", 
                                    {$push: {'Classes.0.registeredMembers': req.query.UID}},
                                    {safe: true, upsert: true}, function(err, model) {
                                        if (model != null) {
                                            console.log('Updated with UID');
                                            res.sendStatus(200);
                                        } else {
                                            console.log('Failed to update');
                                            console.log(err);
                                            res.status(404).send('Failed to update')
                                        }
                                    });
                            };
                        };

                    }
                }
            });
        }
    }
});

});

Thanks to Neil Lunn for pointing me the right direction!

This works:

var where = ["Classes." + i + ".registeredMembers"];
                                obj = { [where]: req.query.UID };

                                gym.findByIdAndUpdate("Members", {$push: obj},
                                    {safe: true, upsert: true}, function(err, model) {
                                        if (model != null) {
                                            console.log('Updated with UID');
                                            res.sendStatus(200);
                                        } else {
                                            console.log('Failed to update');
                                            console.log(err);
                                            res.status(404).send('Failed to update')
                                        }
                                    });
                            };
AzraelPwnz
  • 506
  • 2
  • 12
  • I posted the wrong query code. My apologies guys: `gym.findByIdAndUpdate("Members", {$push: 'Classes.0.registeredMembers'}, {safe: true, upsert: true}, function(err, model) { if (model != null) { console.log('Updated Member_Index with UID'); res.sendStatus(200); } else { console.log('Failed to update'); console.log(err); res.status(404).send('Failed to update Member_Index') } });` – AzraelPwnz Aug 30 '17 at 23:43
  • Could you update the question with that edit? – jackarms Aug 30 '17 at 23:45
  • Done @jackarms . – AzraelPwnz Aug 31 '17 at 00:34
  • I have been at this for 3 days, trying to find a solution. I understand that the positional operator cannot be used for nested arrays, but have tried anyway to no avail haha. If I could pass in a $, then my problem would be solved. – AzraelPwnz Aug 31 '17 at 00:41
  • Thanks Neil Lunn! Did not know the correct terminology to search for (object literal). This works: – AzraelPwnz Aug 31 '17 at 01:08

0 Answers0