Retrieving a specific id from a meteor-rendered template to access a collection field

UPDATE: I have recently included additional code for clarification, marked as * NEW *. To explain the functionality of this code - it involves inputting a series of data into a collection named posts. The displayed output on the postsList template occurs when the timeToEnable field is less than the current time. This enables post delays based on specified dates using this javascript time picker. The issue I am facing lies within the file /client/posts/post_edit.js where I am attempting to set the value of one of the pickers from data in the collection. However, I am uncertain on how to retrieve this data in JavaScript compared to HTML where "{{fieldHere}}" and the postsList template helper are used.

Hopefully, this updated code and information provides better insight into the situation.

ORIGINAL QUESTION.


I have a form that submits 5 fields to a posts collection. On the edit page, the title and content fields auto-populate. However, there are two separate Date/Time pickers. There exists a function that can correctly set the Date/Time pickers with specific data from the posts collection while editing. Due to the specific format in which date/time data is stored (e.g., 2015-05-25T17:50:00.000Z), I have created separate fields in the collection for day, month, and year to utilize a datepicker function.

This particular function will facilitate setting the Date picker.

picker.set('select', new Date(year, month, date));

The challenge arises when trying to retrieve the year, month, and date data based on the ID of the post being edited. While I can display them in HTML using {{title}}, I am unsure about identifying the ID, accessing that post in the collection, and utilizing picker.set accordingly.

Below is the code representing my progress so far:

Client /client/posts/post_submit.js

Template.postSubmit.events({
'submit form': function(e){
 e.preventDefault();
 var post = {
 title: $(e.target).find('[name=title]').val(),
 postContent: $(e.target).find('[name="postContent"]').val(),
 timeToEnable: new Date(year, month, day, hours, minutes),
 timeDisplay: timeDisplay,
 year: year,
 month: month,
 day: day,
 hours: hours
};

// console.log(post.timeToEnable);

Meteor.call('postInsert', post, function(error, result) {
 // display the error to the user and abort
 if (error){
 return alert(error.reason);
}

// show this result but route anyway
if (result.postExists){
 alert('This link has already been posted');
}

Router.go('postPage', {_id: result._id});


});

}

});

/client/posts/posts_list.html * NEW *

<template name="postsList">
 <div class="posts page">
 {{#each posts}}
 {{> postItem}}
 {{/each}}
 </div>
</template>

Server ~/server/publications.js`

Meteor.publish('posts', function() {
 return Posts.find();
});

In conclusion, I would appreciate assistance regarding retrieving the collection fields for posts in postEdit when rendering the template to set the value of the day input picker.

Thank you in advance for your help.

Answer №1

After experimenting with different solutions, I finally found one that worked for me.

client /posts/post_edit.js

Template.post_edit.rendered = function(){
var year = (postObject.year);
var month = (postObject.month) -1;
var day = (postObject.day);
var hours = (postObject.hours);

var $input = $('.datepicker').pickadate();
var $inputTime = $('.timepicker').pickatime();


// Use the picker object directly.
var picker = $input.pickadate('picker');
var pickerTime = $inputTime.pickatime('picker');


picker.set('select', new Date(year, month, day));// Get on screen image
pickerTime.set('select', [hours,0]);// Get on screen image
}

lib /lib/router.js

Router.route('/posts/:_id/edit', {
  name: 'postEdit',
  data: function() {
  postObject = Posts.findOne(this.params._id);


    return postObject;

    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mongoose sparks a confrontation following the preservation of a single document in the database

I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, whe ...

Button inside table cell not showing Bootstrap tooltip

I've implemented a feature where each row in a table has a button that triggers a pop-up modal when clicked. I want these buttons to display tooltips when hovered over and when focused. Below is an example of the HTML structure: <link hr ...

In JavaScript, not all elements are removed in a single iteration, even if the condition is consistently met

I'm currently attempting to compare two arrays containing multiple objects and remove elements based on a condition. To my surprise, while testing in Chrome's console, I noticed that the first array (arr1) is not being emptied even though I am us ...

Personalize the menu item in material ui

Currently, I have a <select> component from Material UI and I am iterating over the menuItem elements. Here is a sample you can reference: here My issue lies in trying to change the background color of each menu item. Although I attempted to do so, ...

Tips for avoiding Client DOM XSS vulnerability in JavaScript

Upon completing a checkmarx scan on my code, I received the following message: The method executed at line 23 of ...\action\searchFun.js collects user input for a form element. This input then passes through the code without proper sanitization ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

How can I generate multiple DIV elements within a for loop using JavaScript?

Can a series of unique divs be created using a for loop? for (var i = 0, n = 4; i < n; i++) { var divTag = document.createElement("div"); divTag.id = "div"i; divTag.innerHTML = Date(); document.body.appendChild(divTag); } Is it expected that this scri ...

Retrieving DOM Element in Angular from Freshly Loaded Template

Recently starting my journey with Angular, I have encountered a challenge when trying to access the DOM from a newly loaded template. Let me explain what's going on - index.html <div class="template" ng-app="myApp" ng-controller="myController"> ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Exploring the Depackaging of ES6 Nested Objects

How can I implement ES6 with Destructuring to give users options? I'm having trouble dealing with nested objects and preventing the defaults from being overwritten by partial objects. Check out this simple example on MDN: function drawES6Chart({si ...

Grails 3.1.9 does not support displaying JavaScript

Having trouble getting the datepicker to display using JavaScript <script> $( "#invoiceDate" ).datepicker({ inline: true, dateFormat: "yy-mm-dd", onSelect: function(datetext){ datetext = datetext+" 00:00:00.0" ...

Issue with Firefox-Android causing dropdown toggle to malfunction

When I manually trigger a dropdown, it closes when any click is performed outside of it (while open). This code works in all browsers except for Firefox on Android. Why does this happen? It seems like the event parameter doesn't reach the function ...

Updating NPM yields no changes

Having trouble updating dependencies in a subfolder of my MERN stack app. Specifically, I am trying to update the dependencies in the client folder where the React code is located. However, when I attempt to update the dependencies in the client folder, it ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

What is the best way to pass cookies between domain and subdomain using nookies?

Recently, I've been facing some challenges with sharing cookies between my app and website while using nookies. Below is the code snippet from my app.mydomain.com file: //setCookies to main domain setCookie(null, 'jwt', login ...

The callbacks in NextAuth do not appear to be functioning

I am currently working on implementing authentication with NextAuth in my Next.js app. I've noticed that the callbacks from the GoogleProvider are not being executed. Even after adding a console log statement, I cannot see any output in the console. A ...

Encountering issues with Visual Studio Code following the integration of the MongoDB API Mongoose into my code

As I delve into the world of web development, I have been exploring databases with MongoDB Atlas and mongoose. Interestingly, my debugging process has hit a bump when using the node.js(legacy) debugger in VS code after importing mongoose with const mongoos ...

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

Traversing through nested arrays within nested objects using AngularJS

In my project, I am utilizing angularjs 1 and dealing with a complex json object that has multiple levels of nesting. My goal is to use ng-repeat in order to access a nested array within the json structure. [{ "information": { "name": "simdi jinki ...

Efficiently managing multiple database updates with PHP and JQuery

Having trouble processing multiple mySQL updates simultaneously? I have 4 select/option boxes fetching data from a db table and I want to update the database onChange using JQuery. It's working with one select module, but adding more causes issues. Th ...