How to handle array of objects in node.js using express and mongodb -
i have 2 collection,
var sub= new schema({ content: string, date: date }); var main= new schema({ subs: [sub] });
i creating , deleting way:
exports.create = function(req, res) { new sub({ content: req.body.content }).save(function(err, sub) { main.update({_id: req.body.mid}, {$push: {subs: sub}}, {upsert: true}, function(err, mmain) { res.redirect('/' + req.body.mid); }); }); }; exports.destroy = function(req, res) { sub.findone({_id: req.params.sid}, function(err, sub) { main.update({_id: req.params.mid}, {$pull: {subs: sub}}, function(err, mmain) { sub.remove(function(err, sub) { res.redirect('/' + req.params.mid); }); }); }); };
so i'm first creating sub object, , use .update $push sub object main collection. however, when delete 1 sub object list, have delete original sub object. there way it? have change 1 sub object instead of having change both sub sits inside main object , original sub object.
well, found out how it. rather suited app use embedded sub have schema , collection deleted sub collection , edited main collection to:
var main= new schema({ subs: [ content: string, date: date ] }); exports.create = function(req, res) { main.update({_id: req.body.mid}, {$push: {subs: {content: req.body.content}}}, {upsert: true},function(err, main) { res.end(); }); };
Comments
Post a Comment