I am new to AngularJS and I was trying to update my MongoDB Database. I am having an issue when I am trying to update an object inside my collection. The following is my attempt at trying to do so:
//listviewFactory is already injected and returns an event object
//I call $scope.put when clicking (ng-click) on a button
$scope.event = listviewFactory.getEvent();
$scope.put = function(event){
var currentUser = {};
if($cookieStore.get('token')) {
currentUser = User.get();
}
event.attendees.push(currentUser);
$http.post('/api/events/' + event._id, event).success(function(data){
for(var i = 0; i < event.attendees.length; i++){
console.log("Attendees: ", event.attendees[i]);
}
$location.path('/');
});
};
I'm just unsure of why my code isn't working. When I do the $http put request, my function is successful and proceeds to perform the console.log. When I print out the attendees array, I saw that the currentUser object is indeed appended to my event.attendees array. However, when I check my database using the Mongo shell, My attendees array is not updated and remains blank. Any ideas on why or where I may be wrong at? Below is also my server side code in how I am routing my application and specifying how to store the information in MongoDB.
module.exports = function(app) {
app.use('/api/events', require('./api/event'));
...
}
module.exports = mongoose.model('Event', EventSchema);
var express = require('express');
var controller = require('./event.controller');
var router = express.Router();
router.get('/', controller.index);
router.put('/:id', controller.update);
// Updates an existing event in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Event.findById(req.params.id, function (err, event) {
if (err) { return handleError(err); }
if(!event) { return res.send(404); }
var updated = _.merge(event, req.body);
updated.save(function (err) {
if (err) { return handleError(err); }
return res.json(200, event);
});
});
};
EDIT: When I console.log currentUser:
Current User:
Resource {$promise: Object, $resolved: false, $get: function, $save: function, $query: function…}
$promise: Object
$resolved: true
__v: 0
_id: "53dd72fb5a24aa781a3cbde8"
email: "test@test.com"
name: "Test User"
provider: "local"
role: "user"
EDIT: Mongoose schema:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var EventSchema = new Schema({
startDate: Date,
endDate: Date,
eventLocation: String,
eventName: String,
attendees: Array
});
I assume you are using mongoose. Try
updated.markModified('attendees');
before
updated.save call.
Regarding pushing the currentUser, do something equivalent to
event.attendees.push({__v: 0
_id: "53dd72fb5a24aa781a3cbde8"
email: "test@test.com"
name: "Test User"
provider: "local"
role: "user"})
i.e just push the relevant fields.