javascript - MongooseJS Not saving to array properly -
i want append value mongoose array array never seems update. following:
in controller, append eventname array eventsattending
so:
$scope.currentuser.eventsattending.push(event.eventname); $http.put('/api/users/' + $scope.currentuser._id, $scope.currentuser) .success(function(data){ console.log("success. user " + $scope.currentuser.name); });
i try update array so:
// updates existing event in db. exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } user.findbyid(req.params.id, function (err, user) { if (err) { return handleerror(res, err); } if(!user) { return res.send(404); } user.markmodified('req.body.eventsattending'); user.save(function (err) { if (err) { return handleerror(res, err);} return res.json(200, user); }); }); };
but array never seems update. i've tried following:
// updates existing event in db. exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } user.findbyid(req.params.id, function (err, user) { if (err) { return handleerror(res, err); } if(!user) { return res.send(404); } var updated = _.merge(user, req.body); updated.markmodified('eventsattending'); updated.save(function (err) { if (err) { return handleerror(res, err);} return res.json(200, user); }); }); };
with approach, array updates properly, when try perform http put after 1 time, error saying error: { [versionerror: no matching document found.] message: 'no matching document found.', name: 'versionerror' }
here userschema:
var userschema = new schema({ name: string, username: string, eventsattending: [{ type: string, ref: 'event'}], });
if appreciated.
my guess object returning _.merge no longer mongoose model , information getting lost in transform. try manually setting of fields coming request , use events.attending.push()
add array, saving updated object , see happens.
your first example markmodified looks wrong. looking @ documentation should name of field modified , appears you've put source location it.
user.markmodified('user.eventsattending')
however should not necessary if use push method mongoose overrides built-in array function track changes.
Comments
Post a Comment