I have an application that deals with events. User need to be logged in to create events, when they do create an event I need to add the event ID to the user.events array. However I am running into difficulty saving events to the users, this is the main issue. I get my other data in my 'events' route that is being redirected to after the event is created.
router.post("/event", isLoggedIn, function (req,res){
// get data from form and add to events array
var title = req.body.title;
var date = req.body.date;
var description = req.body.description;
var venue = req.body.venue;
var photo = req.body.photo;
var category = req.body.category;
//get user data to save to the event.
var owner = {
id: req.user._id,
username: req.user.username
}
var newEvent = {category: category, title: title, date: date, description: description, venue: venue, photos:{link: photo,date: date}, owner: owner};
Event.create(newEvent, function(err, event){
if(err){
console.log(err)
} else {
//This takes the event owner ID and saves it into the Event model
//event.owner.id = req.user._id;
//This takes the event username and saves it into the Event model
event.owner.username = req.user.username;
event.save();
//console.log(event);
//Save the event ID in the user document
User.update({_id: event.owner.id}, function(err,savedData){
savedData.events = {eventId: event._id};
savedData.save();
})
//Add the Event ID to the User model
console.log (owner);
}
});
res.redirect('events');
})
In my model I have User.events as an array, I am not sure if that is an issue, but the error I get is on the redirect to 'events' it tells me that events.forEach is not a function.
Here is the line in the template that is creating the error:
<% events.forEach(function(events){ %>
Here is the 'events' route:
router.get("/events", isLoggedIn, function(req,res){
User.findById(req.user._id).populate("moments").populate("events").exec(function(err,allEvents){
console.log("The id of the user " + req.user._id)
console.log("User ID: " + req.user._id)
if(err){
console.log(err);
console.log("Ummm.... the database may be down?.......")
} else {
// if (allEvents === null){
// res.redirect("/dashboard");
// console.log("nothing in AllEvents");
// console.log(allEvents);
// } else {
console.log("Below are all the events pulled");
//console.log(allEvents)
res.render("eventsList", {events: allEvents});
// }
}
})
});
allEvents
is a plain object, not an Array, so forEach()
and other Array-related methods are not available.
If you want to iterate over the properties of the object, you could instead do Objects.keys(allEvents).forEach(function(key) {
and use allEvents[key]
to get the value for each key. Otherwise, just completely remove the events.forEach(function(events){
(and the associated }
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.