[英]While creating new event trying to save event id to the user who created it…errors
我有一個處理事件的應用程序。 用戶需要登錄才能創建事件,當他們創建事件時,我需要將事件ID添加到user.events數組中。 但是,在將事件保存給用戶方面遇到了困難,這是主要問題。 我在“事件”路由中獲取了其他數據,這些數據在創建事件后將被重定向到。
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});
// }
}
})
});
allEvents
是一個普通對象,而不是Array,因此forEach()
和其他與Array相關的方法不可用。
如果要遍歷對象的屬性,可以改用Objects.keys(allEvents).forEach(function(key) {
並使用allEvents[key]
來獲取每個鍵的值。否則,只需完全刪除events.forEach(function(events){
(和相關的}
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.