node.js - Mongoose nested arrays of schema updates -


shocker, i'm new mongo/mongoose. reading/understanding of mongo better use nested documents instead of normalizing data separate documents. in mind have following schema:

var rowschema = new schema({   value: string });  var columnschema = new schema({   title:  string,   rows: [rowschema] });  var thingschema = new schema({   _id: {     type: string,     unique: true,     'default': shortid.generate   },   name: string,   starttime: date,   endtime: date,   columns: [columnschema]   active: boolean }); 

from ui i'm trying add rowschema, within column/thing schema. understanding mongo work whole top level document. in ui have instance of thingschema, manipulating rows (push etc.), directly manipulate entire document. when sending new version of document updated i've found understanding apparently incorrect.

at first tried update other document:

    exports.update = function(req, res) {   if(req.body._id) { delete req.body._id; }   retrospective.findbyid(req.params.id, function (err, thing) {     if (err) { return handleerror(res, err); }     if(! thing) { return res.send(404); }     var updated = _.merge(thing, req.body);     updated.save(function (err) {       if (err) { return handleerror(res, err); }       return res.json(200, thing);     });   }); }; 

but alas, after viewing many articles don't believe whole document replace work? i've read using $push or $addtoset (which work) , tried hacky stuff (which works) feels dirty:

thing.columns[1].rows.push(fromwire.columns[1].rows[fromwire.columns[1].rows.length-1]); thing.save(function (err) {   if (err) { return handleerror(res, err); }   return res.json(200, retrospective); }); 

i'm nervous having backend controlling push/pop indexing of these array items ui able move indexes around in array , seems i'm setting self failure. best practices this? should not thinking in terms of whole document replacement? should used updating sub documents?? seems data consistency nightmare many clients need receive updated copies every edit.

thanks!


Comments