0

I am trying to create a calendar using Nodejs, EJS and Mongodb wherein one can write events for a particular day. The events get stored in a collection called Names in a mongodb database called Sample Database.

This is the code in app.js file.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const { MongoClient } = require("mongodb");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

const uri =
"mongodb+srv://netTheCoder:welcome@cluster0.ra2eh5p.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
var eventItems = [];
var eventsObj={};
var events_arr = [];
var inputEvent,inputDate;
var added;
 app.get("/calendar",function(req,res){ 
console.log(events_arr);
   res.render('calendar',{newListItem: eventItems, added : added, eventsArr : events_arr});    }) 
app.post("/calendar",function(req,res){
   inputEvent = req.body.eventInput   inputDate = req.body.eventDate;
   eventsObj= {   
   date:inputDate,    
 description: inputEvent  
 }     
events_arr.push(eventsObj) 
console.log(eventsObj);
   // obj={

  //   user :"user1",   
//   events: events_arr   // }   
AddEvents().catch(console.dir);  
  eventItems.push(inputEvent); 
added = true;  
res.redirect("/calendar"); 
})  
async function AddEvents() {   
try {     
const database = client.db('SampleDatabase');     
const names = database.collection('n');      
//Adding events to calendar          
const addedItem = await names.insertOne(eventsObj);   
console.log("Item added successfully")     
console.log(addedItem);     
// Query for a movie that has the title 'Back to the Future'       
}         finally {  
   } }  

async function getEvents() {  
 try {     
const database = client.db('SampleDatabase');     
const names = database.collection('Names');      
//Adding events to calendar          
const addedItem = await names.find();  
 console.log("Item added successfully")     
console.log(addedItem);     

 // const query = { date: "16-12-22"};     
// const event = await names.find(query);    } 
        
finally {   //   
// Ensures that the client will close when you finish/error   //   await client.close();   } }   

server.listen(3000,function(req,res){   console.log("The server is running at port 3000"); }) 

The calendar.js file

 const currentDate = $(".current-date"),
    daysTag = $(".days"),
    prevNextIcons = document.querySelectorAll(".calender-icons span");

//getting the present date, year and month
let date = new Date(),
    currentYear = date.getFullYear(),
    currentMonth = date.getMonth();
console.log(currentMonth)
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];


const renderCalendar = () => {

    const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    let firstDayofMonth = new Date(currentYear, currentMonth, 1).getDay(); 
    let lastDateofMonth = new Date(currentYear, currentMonth + 1, 0).getDate(); 
    let lastDayofMonth = new Date(currentYear, currentMonth, lastDateofMonth ).getDay()
    let lastDateofLastMonth = new Date(currentYear, currentMonth, 0).getDate();
   
    let liTag = "";

    for (let i = firstDayofMonth ; i > 0; i--) {
        liTag += `<li class="day inactive">${lastDateofLastMonth-i +1}</li>`
        
    }

    for (let i = 1; i <= lastDateofMonth; i++) {
        let isToday = i ===  date.getDate() && currentMonth === new Date().getMonth() 
                      && currentYear === new Date().getFullYear() ? "active" :"";
        liTag += `<li class="day ${isToday}">${i}</li>`
    }
   for(let i =lastDayofMonth; i<6 ;i++){
    liTag += `<li class="day inactive">${i-lastDayofMonth +1}</li>`
   }

    currentDate.text(`${months[currentMonth]} ${currentYear}`);
    daysTag.html(liTag)
}
renderCalendar();

prevNextIcons.forEach(icon => {
    icon.addEventListener("click", () => {
        if (icon.id === "prev") {

            if (currentMonth === 0) {
                currentMonth = 11;
                currentYear = currentYear - 1;
            } else {
                currentMonth = currentMonth - 1;
            }

            console.log(currentMonth);
            renderCalendar();
            dateClicked();
        } else {

            if (currentMonth === 11) {
                currentMonth = 0;
                currentYear = currentYear + 1;
            } else {
                currentMonth = currentMonth + 1;
            }
            console.log(currentMonth);

            renderCalendar();
            dateClicked();
        }

    })
})

let dateObj = new Date();
let today = String(dateObj.getDate()).padStart(2, '0');
$(".event-date").text(today +" " + months[currentMonth]);

let eventLi ="";
var eventAddedDay;
dateClicked();
function dateClicked(){
    selectedDate = document.querySelectorAll(".day")
    selectedDate.forEach(day=>{
        day.addEventListener("click",()=>{
        var clickedDate = day.textContent;
        $(".event-date").text(clickedDate + " " + months[currentMonth]);
        let clickedMonth = currentMonth+1;
        let output = currentYear + '-' + clickedMonth + '-' + clickedDate;
       console.log("clicked");
        $(".events-date").attr('value' ,output );
        })
    })
}
    


 

The code for calendar in calendar.ejs file. This file is linked to calendar.js file.

<div class="calendar">
        <ul class="weeks">
            <li>Sun</li>
            <li>Mon</li>
            <li>Tues</li>
            <li>Wed</li>
            <li>Thurs</li>
            <li>Fri</li>
            <li>Sat</li>
        </ul>
        <ul class="days"></ul>
    </div>
  </div>
</div>
<div id = "events">
    <h3 class="event-date"></h3>
    <ul type="disc" class="events">
       
        <% for(let i = 0; i<newListItem.length; i++){ %>
        <li> <%= newListItem[i] %></li>
        <% } %>
           
       
            
         
    </ul>
    <p class="retured-date" hidden>
        
    </p>
    <form method="post" action="/calendar">
    <input class="events-date" type="date" name="eventDate" placeholder="Date">
    <input class="event-input" type="text" name="eventInput" placeholder="Your event">
    <button type="submit" class="btn btn-outline-dark">Add</button>
</form>
</div>

I was trying to send this data through ejs to my HTML calendar page. So when I click on a day in the calendar the events stored in the database for that particular day should be displayed in the events section . I don't know why but I have tried all possible ways to tackle this but none of them seem to work.

98k374
  • 1
  • 1

0 Answers0