I want to convert to date my coloumn date that I declare like String in my mongoDB schema

I want to convert to date my coloumn date that I declare like String in my mongoDB schema

pumbapumba Posts: 3Questions: 1Answers: 0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown: I dont have message error
Description of problem: When filtering with searchbuilder, regarding the date, I should have between and not between in the condition. But in my MongoDB schema, I declared the date as a string, so in the filter, it is treated as a string. I want to convert the date to the datetime type before the searchbuilder filter without changing my database declaration.

Answers

  • pumbapumba Posts: 3Questions: 1Answers: 0
    edited March 2023

    my script : script.

          $(document).ready(function() {
            var table = $('#myTableList').DataTable({
                dom: 'QBlfrtip',
                searchBuilder:{
                  columns: [
                    {
                        label: 'Date numérisation',
                        name: 'scanning_date',
                        type: 'datetime',
                        format: 'DD/MM/YYYY HH:mm:ss',
                        value: function(value) {
                            return moment(value, 'DD/MM/YYYY HH:mm:ss').toDate();
                        }
                    },
                    0, 1, 2, 3, 4, 5
                ] 
                },     
                buttons: [
                  'copy', 'csv', 'excel', 'pdf', 'print',
                ],
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                pageLength: 10
              });
            
            table.searchBuilder.container().prependTo(table.table().container());
      
            // Add a listener to the date range inputs
            $('#fromDate, #toDate').change(function() {
              // Get the from and to dates from the inputs
              var fromDate = $('#fromDate').val();
              var toDate = $('#toDate').val();
              // Convert the dates to Date objects
              var from = moment(fromDate, 'DD/MM/YYYY').toDate();
              var to = moment(toDate, 'DD/MM/YYYY').toDate();
    
              // Apply the filter to the table
              table.column('scanning_date:name')
                  .search(from.getTime() + ' to ' + to.getTime())
                  .draw();
            });
          }); 
    

    my function to register data on mu database :

    exports.processOkFiles = async (req, res) => {
      const OK_DEST = process.env.PROCESSDONEPATH;
      const EXTENSION = ".txt";
    
      const destinationPath = path.join(__dirname, OK_DEST);
    
      //passsing directoryPath and callback function
      const allDirectories = getSubDirectories(process.env.DONEPATH);
      allDirectories.forEach((directory) => {
        let pathFile = `${process.env.DONEPATH}${directory}`;
        pathFile = pathFile + "\\";
        const matchedFiles = [];
        fs.readdir(pathFile, function (err, files) {
          //handling error
          if (err) {
            return console.log("Unable to scan directory: " + err);
          }
          if (files.length == 0) {
            return console.log("No file to proceed");
          }
          for (const file of files) {
            const fileExt = path.extname(file).toLowerCase();
            if (fileExt === EXTENSION) {
              matchedFiles.push(file);
            }
          }
    
          
          //listing all files using forEach
          matchedFiles.forEach(function (file) {
            // Do whatever you want to do with the file
            filedata = getFiles(pathFile + file);
            let data = filedata.split("|");
            // Create a kcpSupervisor
            const kcpSupervisor_ = new _kcpSupervisor({
              destination: data[0],
              subject: data[1],
              sender_email: data[2],
              index: data[3],
              doc_seq_Number: data[4],
              doc_filename: data[5],
              doc_number: data[6],
              batch_sheets_number: data[7],
              doc_sheets_number: data[8],
              nature_spark: data[9],
              sheet_endorser: data[10],
              scanning_date: moment(data[11], "YYYY-MM-DD HH:mm:ss").toDate(),
              scanning_site: data[12],
              flow_code: data[13],
              workstation_id: data[14],
              archive_site: data[15],
              rename_pdf: data[16],
              batch_name: data[17],
              direction_code: data[18],
              file_path: data[19],
              is_ok: true,
            });
            // Save kcpSupervisor in the database
            kcpSupervisor_
              .save()
              .then((data) => {
                moveFile(pathFile + file, process.env.PROCESSDONEPATH);
              })
              .catch((err) => {});
          });
        });
      });
    
    my table using datatables : table#myTableList.table.mt-5
            thead
              tr
                th Date numérisation
                th Mail destination
                th Emetteur
                th subject 
                th Index
                th Nom pli
                th Site numérisation 
                th Endosseur 
                th Site archivage 
                th Code direction 
                th Nature spark 
                th Nom lot
    
                th Etat Pli
                th Action
            tbody
               each item, i in items
                    tr.table-secondary
                        td #{item.scanning_date}
                        td #{item.destination}
                        td #{item.sender_email}
                        td #{item.subject}
                        td #{item.index}
                        td #{item.doc_filename}
                        td #{item.scanning_site}
                        td #{item.sheet_endorser}
                        td #{item.archive_site}
                        td #{item.direction_code}
                        td #{item.nature_spark}
                        td #{item.batch_name}
                        td 
                          .progress
                            if item.is_ok === true 
                              .progress-bar.bg-success(role='progressbar' style='width: 100%' aria-valuenow='100' aria-valuemin='0' aria-valuemax='100')
                            if item.is_ok === false 
                              .progress-bar.bg-danger(role='progressbar' style='width: 100%' aria-valuenow='100' aria-valuemin='0' aria-valuemax='100')
                        td
                          a(href="/details/" + item._id)
                            button.btn.bg-navyblue.text-white(type='button') Détails
                            //-button.btn.btn-success(type='button') Modifier
                          a(href="/delete/" + item._id)
                            button.btn.bg-red.text-white(type='button') Supprimer
                              .modal(tabindex='-1')
                                //- .modal-dialog
                                //-   .modal-content
                                //-     .modal-header
                                //-       h5.modal-title Modal title
                                //-       button.btn-close(type='button' data-bs-dismiss='modal' aria-label='Close')
                                //-     .modal-body
                                //-       p Modal body text goes here.
                                //-     .modal-footer
                                //-       button.btn.btn-secondary(type='button' data-bs-dismiss='modal') Close
                                //-       button.btn.btn-primary(type='button') Save changes
    

    Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • pumbapumba Posts: 3Questions: 1Answers: 0

    Je vous remerci d'avance

  • colincolin Posts: 15,112Questions: 1Answers: 2,583

    You should just be able to use Luxon or Moment to specify the date format.

    Those examples should get you going, but if not, we're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

Sign In or Register to comment.