我有一個處理事件的應用程序。用戶需要登錄才能創建事件,當他們確實創建了一個事件時,我需要將事件ID添加到user.events數組中。然而,我很難將事件保存給用戶,這是主要問題。我在我的「活動」路線中獲取了其他數據,這些數據在事件創建後被重定向到。創建新事件嘗試將事件ID保存到創建它的用戶...錯誤
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');
})
在我的模型我有User.events作爲一個數組,我不知道這是一個問題,但我得到的錯誤是對重定向到「事件」它告訴我,events.forEach是不是功能。
這裏是在被產生錯誤的模板中的線:
<% events.forEach(function(events){ %>
這裏是「事件」路線:
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});
// }
}
})
});
如果您的錯誤發生在'events'路徑處理程序中,那麼您應該發佈該文件,而不是您已發佈的內容。 – mscdex
謝謝,貼出更多細節。 – illcrx
你的'console.log(allEvents)'顯示什麼和/或'console.log(typeof allEvents)'顯示了什麼?如果後者顯示'object','console.log(Array.isArray(allEvents))'顯示什麼? – mscdex