Mongo : Array of Objects

Mongo : Array of Objects

Voici un premier partage de snippets ! Il s'agit de mettre à jour un tableau d'objets contenus dans un objet mongo. Un petit travail casse pied mais très récurrent, autant se le garder dans un coin.

Add one object in array
/******************************************************
 *** Add One Object in array of objects
 *** req.body : {
 ***    _id    :  ID of object which contains the table 'myArray'
 ***    object :  Object to push in Table
 *** }
 ******************************************************/
exports.AddOneObjectToArray = function(req, res, next) {
    Data.findOneAndUpdate({
            _id: req.body._id
        }, {
            $push: {
                myArray: req.body.object
            }
        }, {
            safe: true,
            upsert: false
        },
        function(err, datas) {
            if (err){
                console.log(err);
                next();
            }
            // return new data
            res.json(datas);
        });
};
Del one object in array
/******************************************************
 *** Del One Object in array of objects
 *** req.body : {
 ***    _id    :  ID of object which contains the table 'myArray'
 ***    ObjId  :  ID of object to Delete
 *** }
 ******************************************************/
exports.DelOneObjectInArray = function(req, res, next) {
    Data.update({
            _id: req.body._id
        }, {
            $pull: {
                'myArray': {
                    _id: req.body.ObjId
                }
            }
        },
        function(err) {
            if (err){
                console.log(err);
                next();
            }
            // return OK
            res.json('OK');
        });
};
Update one object in array
/******************************************************
 *** Update Key(s) of one object in array
 *** req.body : {
 ***    _id  :  ID of object to update in the table 'myArray'
 ***    text :  Value of key to update
 *** }
 ******************************************************/
exports.UpdateOneObjectInArray = function(req, res, next) {
    Data.update({
        'myArray._id': req.body.id
    }, {
        $set: {
            'myArray.$.text': req.body.text,
        }
    }, function(err, data) {
            if (err){
                console.log(err);
                next();
            }
            // return number
            res.json(data);
        });
};

En espérant que cela soit utile ;).