How to Access This.props.route.params in constructor

my first page pushing an array with some data to next page ,I want to use that data in RenderItem for flatlist.I tried bind event but its also not worked for me ,any help would be appriciated .

enter code here
export default class mainPage extends React.Component<any, any> {

  constructor(props: any) {
    super(props)
    this.state = {
      text: '',
      slots: [],
      screen: 'screen1',
      vehicleNumber: '',
      parkingLot: [],
      selectedSlot: '',
    }
  }

  createSlot() {
    let tempdata: any[] = []
    for (let i = 0; i < parseInt(this.state.text); i++) {
      tempdata.push({
        allocated: false,
        timestamp: new Date(),
      })
    }
    this.setState(
      {
        slots: [
          ...this.state.slots,
          {
            id: (Math.random() + 1).toString(36).substring(7),
            count: parseInt(this.state.text),
            data: tempdata,
          },
        ],
        text: '',
        screen: 'screen2',
      },
      () => {
        this.props.navigation.navigate('floor', {
          slots: this.state.slots,
        })
      },
    )
  }
  // componentDidMount() {

  //   this.setState({ parkingLot: [...this.parkingLot] })

  // }
  park = () => {
    console.log('jcjhj', this.state.parkingLot)
    var item = this.state.slots[
      Math.floor(Math.random() * this.state.slots.length)
    ]
    console.log('Parkinglot', this.state.parkingLot, item)
    console.log('Slots', this.state.slots)
    if (this.state.slots) {
    }

    // this.setState({
    //   parkingLot: [
    //     ...this.state.parkingLot,
    //     { carnumber: this.state.vehicleNumber },
    //   ],
    // })
  }
  renderItem(item: any) {
    return (
      <TouchableOpacity
        style={styles.Slotinput}
        onPress={() =>
          this.setState({ screen: 'screen3', selectedSlot: item.id })
        }
      >
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot ID:-{item.id}
        </Text>
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot Count:-{item.count}
        </Text>
      </TouchableOpacity>
    )
  }
  renderItem1(item: any) {
    return (
      <View style={styles.Slotinput}>
        <Text>{item.allocated ? 'Allocated' : 'Available'}</Text>
        {this.state.parkingLot.map((e: any) => {
          return <Text>{e.carnumber}</Text>
        })}
      </View>
    )
    //   )
    // }
    // return demo
  }

  render() {
    return (
      <View>
        {this.state.screen === 'screen1' && (
          <View style={styles.form}>
            <TextInput
              style={styles.input}
              placeholder="Enter A value for slot"
              onChangeText={(text: any) => this.setState({ text })}
              value={this.state.text}
            />
            <TouchableOpacity
              style={
                this.state.text && this.state.text
                  ? styles.addItemButton
                  : styles.BlurItemButton
              }
              disabled={this.state.text == ''}
              onPress={() => this.createSlot()}
            >
              <Text style={styles.buttonText}>Submit</Text>
            </TouchableOpacity>
          </View>
        )}
        {/* {this.state.screen === 'screen2' && (
          <>
            <Text onPress={() => this.setState({ screen: 'screen1' })}>
              Back
            </Text>
            <FlatList
              data={this.state.slots}
              renderItem={({ item }) => this.renderItem(item)}
              keyExtractor={(item) => item.id}
            />
          </>
        )} */}
        {/* {this.state.screen === 'screen3' && (
          <>
            <Text onPress={() => this.setState({ screen: 'screen2' })}>
              Back
            </Text>
            <>
              {}
              <TextInput
                placeholder="Vechicle Number"
                style={styles.input}
                value={this.state.vehicleNumber}
                onChangeText={(vehicleNumber: any) =>
                  this.setState({ vehicleNumber })
                }
                // onChangeText={data => this.setState({ vehicleNumber: data })}
              ></TextInput>
            </>

            <TouchableOpacity
              style={styles.addItemButton}
              onPress={() => this.park()}
            >
              <Text>Park Vechicle</Text>
            </TouchableOpacity>

            {this.state.slots
              ?.filter((i: any) => i.id === this.state.selectedSlot)
              ?.map((item: any, index: number) => {
                return (
                  <View key={index}>
                    <FlatList
                      data={item.data}
                      renderItem={({ item }) => this.renderItem1(item)}
                      keyExtractor={(item, index) => index.toString()}
                    />
                  </View>
                )
              })}
          </>
        )} */}
      </View>
    )
  }
}

Here is my floor.tsx page(next page)

enter code here
export default class floor extends Component<any, any> {
handleslot: any
constructor(props: any) {
super(props)
// console.log(‘SLOTDATA::–‘, props.route.params)

    this.state = {
      text: '',
      slots: [],
      screen: 'screen1',

      selectedSlot: '',
    }
    // let slo: Array<any> = this.props.route.params
    // console.log('propdata-->', slo)
    // this.setState({
    //   slo: [],
    // })
  }

  renderItem=(item: any)=> {
    console.log('item', item)

    return (
      <TouchableOpacity
        style={styles.Slotinput}
        onPress={() =>
          this.setState({ screen: 'screen3', selectedSlot: item.id })
        }
      >
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot ID:-{item.id}
        </Text>
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot Count:-{item.count}
        </Text>
      </TouchableOpacity>
    )
  }
  render() {
    return (
      <View>
        <Text onPress={() => this.props.navigation.goBack()}>Back</Text>

        <FlatList
          data={this.props.route.params}
          renderItem={({ item }) => 
          this.renderItem(item)}
          keyExtractor={(item) => item.id}
        />
      </View>
    )
  }
}

Trailing and leading commas added issue

I am calling a function from jsx as xyz(id) inside the <img src = "xyz(id)" />. In the calling function, I am retrieving the image value through a map as

const xyz = (id) =>{
     return abc.map(a => {
         if(a.id === id){
             if(a.url){
                 return a.url;
                 }
             }
         })
     }

When I inspect the img element trailing and leading commas are being appended after the return statement as “..returned_url..”.

Can’t set textContent of a customised built-in element except in timeout

I’m making a customised element that automatically localises it’s visual text representation:

class LocalDate extends HTMLTimeElement {
    // Specify observed attributes so that
    // attributeChangedCallback will work
    static get observedAttributes() {
        return ["datetime"];
    }   

    constructor() {
        // Always call super first in constructor
        const self = super();

        this.formatter = new Intl.DateTimeFormat(navigator.languages, { year: "numeric", month: "short", day: "numeric" });

        return self;
    }

    connectedCallback() {
        this._upgradeProperty("datetime");
    }

    attributeChangedCallback(name, oldValue, newValue) {
        if (name === "datetime") {
            this.textContent = "";
            const dateMiliseconds = Date.parse(newValue);
            if (!Number.isNaN(dateMiliseconds)) {
                const dateString = this.formatter.format(new Date(dateMiliseconds));
                // Bizarrly, this doesn't seem to work without doing this in a timeout?!?!
                setTimeout(() => this.textContent = dateString);
            }
        }
    }

    _upgradeProperty(prop) {
        if (this.hasOwnProperty(prop)) {
            let value = this[prop];
            delete this[prop];
            this[prop] = value;
        }
    }

    set datetime(value) {
        if (value instanceof Date) {
            this.setAttribute("datetime", value.toISOString());
        } else {
            this.removeAttribute("datetime");
        }
    }

    get datetime() {
        const dateMiliseconds = Date.parse(this.getAttribute("datetime"));
        if (Number.isNaN(dateMiliseconds)) {
            return null;
        }
        return new Date(dateMiliseconds);
    }
}

customElements.define('local-date', LocalDate, { extends: "time" });
<time is="local-date" datetime="2022-01-13T07:13:00+10:00">13 Jan 2022 - Still here</time>

The kicker is this line of code in the attributeChangedCallback:

setTimeout(() => this.textContent = dateString);

If it’s instead replaced with the more obvious:

this.textContent = dateString

Then instead of appearing as a date, the element displays the date string in addition to the text that was already in the element.

I’ve reproduced this in both Firefox and Chrome – any ideas what’s going on here?

My Bad Search Algorithm (RegExp and JavaScript)

I am making a static site in vanilla HTML5, CSS3, and JavaScript (ES6). I have made a user-facing search function using a sitemap (stored as a JS variable), regexes, and JS. I’m not very good at regexes or JS. It works sort of okay, but it’s weird. Here’s an example:

page = {
"titles":["Page Title"], 
"headers":["Header 1","Header 2","Header 3"], 
"text":"This is a gigantic string that is all the text from the page body after I stripped out any HTML tags."
}

If, in my IDE, I search sitemap.js for the string “How to Use This Guide” it turns up 7 results. Page 1 has a matching header and two matching strings in the page text. Page 2 has a matching title, a matching header, and two matches in the text.

If I use the Search function in my site (which in turn searches the same sitemap.js file) it only turns up Page 1, and only displays one of the two matches in Page 1’s text. The expected behavior is to turn up Page 1 with two matches and Page 2 with two matches. (Also, Page 2 should be displayed before Page 1 since Page 2 has a matching title, which takes priority.)

Here is the section of sitemap.js text with all 7 hits (some irrelevant text removed to shorten it):

“headers”:[“Falcons Onboarding Guide”,”Introduction”,”How to Use This Guide“],”text”:” Home Page Falcons Onboarding Guide Editing the Guide . How to Use This Guide Use the navigation menu on the please see the How to Use This Guide page. “},{“name”:”how-to-use-guide.html”,”lastModified”:”1/12/2022″,”path”:”pages/how-to-use-guide.html”,”titles”:[“How to Use This Guide“],”headers”:[“How to Use This Guide“,”Purpose of the Guide”,”Sharing and Accessing the Guide”],”text”:” How to Use This Guide How to Use This Guide Purpose Sharing and Accessing

Here is the HTML for the search bar:

<form id="search-form" class="search" onsubmit="search(this.getElementsByTagName('input')[0].value);return false;">
   <input type="text" placeholder="Search">
   <button><i class="magnifying-glass"></i></button>
</form>

Here is the JS code for the search function :

// Adapted from https://gomakethings.com/how-to-create-a-vanilla-js-search-page-for-a-static-website/ 
function search(query) {
    event.preventDefault();
    let regx = new RegExp(query, 'gi');
    let priority1 = [];
    let priority2 = [];
    let priority3 = [];
    
    // search all pages in the JSON for the query text and return hits
    sitemap.forEach(function (page) {
        if (regx.test(page.text)) {
            page.hits = [...page.text.matchAll(regx)].map(a => page.text.slice(a.index > 10 ? a.index - 10 : 0, a.index + 100 > page.text.length ? page.text.length : a.index + 100).replace(new RegExp(query, 'i'), '<strong>' + a[0] + '</strong>'));

            // sort by priority
            if (regx.test(page.titles)) {
                priority1.push(page); 
            } else if (regx.test(page.headers)) {
                priority2.push(page);
            } else {
                priority3.push(page);
            }
        }
    });
    
    let searchResults = [].concat(priority1, priority2, priority3);
    let resultsDiv = document.getElementById('search-results');
    resultsDiv.innerHTML = searchResults.length < 1 ? createNoResultsHtml(query) : createResultsHtml(searchResults);
};

I’ve spent many, many hours on this search function, as well as the “sitemap generator” util that reads the HTML files and strips them of the HTML. I’ve gotten it to a point where it is usable, but buggy. I also can’t figure out why there are frequently some pages that turn up in the search results, but have no “hits.” So they pass the if (regx.test(page.text)) { but fail the following [...page.text.matchAll(regx)]. And some pages don’t make it into the search results at all.

It’s not the HTML generation logic, because when I console.log() the searchResults, it matches exactly what the HTML displays — pages missing from the HTML are missing from the searchResults, hits missing from the HTML are missing from the searchResults.page.hits[]

If some kind soul(s) can help me with this, I would be SO GRATEFUL I can’t even put it into words. TT__TT

Trying to implement Ajax comments in WordPress, getting WP error

I’m trying to implement Ajax for my comments in WordPress, using this tutorial. But I’m running into issues when integrating the code from the tutorial into my own pre-built theme. The issue is that I either get a WP error of ‘Duplicate comment detected; it looks as though you’ve already said that!’or a standard 500 error. Here’s what I’ve got:

Here’s what my ajax-comments.js file looks like:

 * Let's begin with validation functions
 */
 jQuery.extend(jQuery.fn, {
    /*
     * check if field value lenth more than 3 symbols ( for name and comment ) 
     */
    validate: function () {
        if (jQuery(this).val().length < 3) {jQuery(this).addClass('error');return false} else {jQuery(this).removeClass('error');return true}
    },
    /*
     * check if email is correct
     * add to your CSS the styles of .error field, for example border-color:red;
     */
    validateEmail: function () {
        var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/,
            emailToValidate = jQuery(this).val();
        if (!emailReg.test( emailToValidate ) || emailToValidate == "") {
            jQuery(this).addClass('error');return false
        } else {
            jQuery(this).removeClass('error');return true
        }
    },
});
 
jQuery(function($){

    /*
     * On comment form submit
     */
    $( '#commentform' ).submit(function(){
    
        // define some vars
        var button = $('#submit'), // submit button
            respond = $('#respond'), // comment form container
            commentlist = $('.comment-list'), // comment list container
            cancelreplylink = $('#cancel-comment-reply-link');
            
        // if user is logged in, do not validate author and email fields
/*
        if( $( '#author' ).length )
            $( '#author' ).validate();
        
        if( $( '#email' ).length )
            $( '#email' ).validateEmail();
*/
            
        // validate comment in any case
        $( '#comment' ).validate();
        
        // if comment form isn't in process, submit it
        if ( !button.hasClass( 'loadingform' ) && !$( '#author' ).hasClass( 'error' ) && !$( '#comment' ).hasClass( 'error' ) ){
            
            // ajax request
            $.ajax({
                type : 'POST',
                url : html5_comment_params.ajaxurl, // admin-ajax.php URL
                data: $(this).serialize() + '&action=ajaxcomments', // send form data + action parameter
                beforeSend: function(xhr){
                    // what to do just after the form has been submitted
                    button.addClass('loadingform').val('Loading...');
                },
                error: function (request, status, error) {
                    if( status == 500 ){
                        alert( 'Error while adding comment' );
                    } else if( status == 'timeout' ){
                        alert('Error: Server doesn't respond.');
                    } else {
                        // process WordPress errors
                        var wpErrorHtml = request.responseText.split("<p>"),
                            wpErrorStr = wpErrorHtml[1].split("</p>");
                            
                        alert( wpErrorStr[0] );
                    }
                },
                success: function ( addedCommentHTML ) {
                
                    // if this post already has comments
                    if( commentlist.length > 0 ){
                    
                        // if in reply to another comment
                        if( respond.parent().hasClass( 'comment' ) ){
                        
                            // if the other replies exist
                            if( respond.parent().children( '.children' ).length ){  
                                respond.parent().children( '.children' ).append( addedCommentHTML );
                            } else {
                                // if no replies, add <ol class="children">
                                addedCommentHTML = '<ol class="children">' + addedCommentHTML + '</ol>';
                                respond.parent().append( addedCommentHTML );
                            }
                            // close respond form
                            cancelreplylink.trigger("click");
                        } else {
                            // simple comment
                            commentlist.append( addedCommentHTML );
                        }
                    }else{
                        // if no comments yet
                        addedCommentHTML = '<ol class="comment-list">' + addedCommentHTML + '</ol>';
                        respond.before( $(addedCommentHTML) );
                    }
                    // clear textarea field
                    $('#comment').val('');
                },
                complete: function(){
                    // what to do after a comment has been added
                    button.removeClass( 'loadingform' ).val( 'Post Comment' );
                }
            });
        }
        return false;
    });
});```

I've registered and enqueued it in my *functions.php* file, like so:

```add_action( 'wp_enqueue_scripts', 'misha_ajax_comments_scripts' );

function misha_ajax_comments_scripts() {
 
    // I think jQuery is already included in your theme, check it yourself
    wp_enqueue_script('jquery');
 
    // just register for now, we will enqueue it below
    wp_register_script( 'ajax_comment', get_stylesheet_directory_uri() . '/ajax-comment.js', array('jquery') );
 
    // let's pass ajaxurl here, you can do it directly in JavaScript but sometimes it can cause problems, so better is PHP
    wp_localize_script( 'ajax_comment', 'html5_comment_params', array(
        'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php'
    ) );
 
    wp_enqueue_script( 'ajax_comment' );
}

and have also leveraged the custom function that my theme uses for comments (also in functions.php):



add_action( 'wp_ajax_ajaxcomments', 'html5blankcomments' ); // wp_ajax_{action} for registered user
add_action( 'wp_ajax_nopriv_ajaxcomments', 'html5blankcomments' ); // wp_ajax_nopriv_{action} for not registered users

// Custom Comments Callback
function html5blankcomments($comment, $args, $depth)
{
    
    $comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
    
    extract($args, EXTR_SKIP);
    
    if ( is_wp_error( $comment ) ) {
        $error_data = intval( $comment->get_error_data() );
        if ( ! empty( $error_data ) ) {
            wp_die( '<p>' . $comment->get_error_message() . '</p>', __( 'Comment Submission Failure' ), array( 'response' => $error_data, 'back_link' => true ) );
        } else {
            wp_die( 'Unknown error' );
        }
    }

    if ( 'div' == $args['style'] ) {
        $tag = 'div';
        $add_below = 'comment';
    } else {
        $tag = 'li';
        $add_below = 'div-comment';
    }
    
    /*
     * Set Cookies
     */
    $user = wp_get_current_user();
    do_action('set_comment_cookies', $comment, $user);
    
    $GLOBALS['comment'] = $comment;
?>
    <!-- heads up: starting < for the html tag (li or div) in the next line: -->
    <<?php echo $tag ?> <?php comment_class(empty( $args['has_children'] ) ? '' : 'parent') ?> id="comment-<?php comment_ID() ?>">
    <?php if ( 'div' != $args['style'] ) : ?>
    <div id="div-comment-<?php comment_ID() ?>" class="comment-body">
    <?php endif; ?>
    
    <div class="comment-author vcard">
    
    <?php printf(__('<cite class="fn">%s</cite><span class="says"> </span'), get_comment_author_link()) ?><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"></a>
    
        <?php
                        printf( _x( '%s ago', '%s = human-readable time difference', 'your-text-domain' ), human_time_diff( get_comment_time( 'U' ), current_time( 'timestamp' ) ) );
                        ?>
    </div>
    

    

    <?php comment_text() ?>
    
    <?php if( get_field('commenter_rating_number', $comment) ): ?>
            
            <span class="commenter-rating"><ion-icon name="star"></ion-icon><?php the_field('commenter_rating_number', $comment); ?></span>
            
        <?php endif; ?>
    
    <div class="comment-meta commentmetadata"><?php edit_comment_link(__('(Edit)'),'  ','' );
        ?>
    </div>

    <div class="reply">
    <?php comment_reply_link(array_merge( $args, array('add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
    </div>
    <?php if ( 'div' != $args['style'] ) : ?>
    </div>
    <?php endif; ?>
    <div class="separator"></div>
<?php }

Finally, this is the code that outputs it in the theme itself – the comments.php file:

    'title_reply' => '',
    // Redefine your own textarea (the comment body).
        'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comments', 'noun' ) . '</label><textarea id="comment" name="comment" aria-required="true" placeholder="What are your thoughts?"></textarea></p>',
)); ?>



<?php if (have_comments()) : ?>

    <h5><?php comments_number(); ?></h5>

    <ul class="comment-list">
        <?php wp_list_comments('type=comment&callback=html5blankcomments'); // Custom callback in functions.php ?>
    </ul>

<?php elseif ( ! comments_open() && ! is_page() && post_type_supports( get_post_type(), 'comments' ) ) : ?>

    <p><?php _e( 'Comments are closed here.', 'html5blank' ); ?></p>

<?php endif; ?>

Any thoughts? I’m looking at the variables that are being passed and everything seems correct, but with those errors I feel like I might be overlooking something just as simple as that.

Any help is immensely appreciated.

Reverting to a “default” jquery function after mouseout

I’m making some boxes move around randomly when the cursor is not over the div that contains them. They will only follow the mouse when it is “hovering” over div.
However I am trying to make the boxes revert to their random “default” movement after the mouseout. If the user scrolls over the div, then the images follow again. I know the function I am trying to use looks like this but somehow I can’t seem to make it work.

<script>
$(document).ready(function(){
  $("(boxes ref)").mouseover(function(){
    (follow cursor)
  });
  $("(boxes ref)").mouseout(function(){
    (random movement)
  });
});
</script>

Original code:

<!DOCTYPE html>
<html>
<head>
<style>

div#container {height:500px;width:500px;}

.a {

position:fixed;
    
}
.b {

position:fixed;
    
}
.c {

position:fixed;
    
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

$(document).ready(function() {
    animateDiv($('.a'));
        animateDiv($('.b'));
        animateDiv($('.c'));

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv($target) {
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $target.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv($target);
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.03;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}

</script>
</head>
<body>

<div id="container">
 <img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='a' id='image'>
  <img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='b' id='image2'>
 <img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='c' id='image3'>
</div>

<script>

$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
    $("#image").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});

</script>

<!-- make the images follow the cursor -->
<script>

$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
    $("#image2").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});

</script>

<script>

$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
    $("#image3").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});

</script>

</body>
</html>

Thanks

Mongoose not saving document, getting “MongoClient must be connected” error

I am trying to connect to MongoDb using mongoose. Here is the code I am using to connect:

controller.js

const conn = mongoose.createConnection(db, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        })

        conn.once('open', () => {
            console.log(`${req.body.db} DB connected`)
            const model = conn.model(`item`, Item, req.body.collection)

            let stuff = uploadToS3(req.files)
            stuff.then(paths => {
                const newItem = new model({
                    nameOfItem: req.body.name,
                    pictures: paths,
                    description: req.body.description,
                    year: req.body.year,
                    favorite: req.body.favorite
                })

                //save data to MongoDB
                newItem.save()
                    .then(item => {
                        console.log(item)
                        res.json(item)
                    })
                    .catch(err => console.log(err))
                conn.close()
            })
        })

I don’t think this matters, but I will state it anyway. I am using a single schema for several different databases and collections. Here is the schema:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const pictureSchema = new Schema({
    name: String,
    path: String
})
const itemSchema = new Schema({
    nameOfItem: { type: String, required: true },
    pictures: [pictureSchema],
    description: String,
    year: String,
    favorite: {type: Boolean, default: false}
})

module.exports = itemSchema

And I am pulling the schema into the controller using this:

const Item = require('../models/item.model')

Here is the output:

bottles DB connected
{
  fieldname: 'photos',
  originalname: 'DSCN5104.JPG',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: 'uploads/',
  filename: '1c17e793b340658f14bcc92c98444d95',
  path: 'uploads\1c17e793b340658f14bcc92c98444d95',
  size: 2107729
}

MongoNotConnectedError: MongoClient must be connected to perform this operation
    at getTopology (C:UsersuserOneDriveDesktopProjectservernode_modulesmongodblibutils.js:367:11)
    at Collection.insertOne (C:UsersuserOneDriveDesktopProjectservernode_modulesmongodblibcollection.js:150:82)
    at NativeCollection.<computed> [as insertOne] (C:UsersuserOneDriveDesktopProjectservernode_modulesmongooselibdriversnode-mongodb-nativecollection.js:200:33)
    at model.Model.$__handleSave (C:UsersuserOneDriveDesktop\Projectservernode_modulesmongooselibmodel.js:294:33)
    at model.Model.$__save (C:UsersuserOneDriveDesktopProjectservernode_modulesmongooselibmodel.js:374:8)
    at C:UsersuserOneDriveDesktopProjectservernode_moduleskareemindex.js:281:16
    at C:UsersuserOneDriveDesktopProjectservernode_moduleskareemindex.js:78:15
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
bottles DB closed

What confuses me is that it says that it is connected and giving me that error at the same time. Any help is appreciated.

nodemon ERROR app crashed – waiting for file changes before starting

I’m on the project logging page using JWT in node js. But today, when I was running the “nodemon index or nodemon index.js” command on vscode terminal, I got a message like this.

PS E:OneDriveDocumentsJWT AUTHjsonwebt> nodemon index          
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`                        
[nodemon] watching path(s): *.*                                                     
[nodemon] watching extensions: js,mjs,json                        
[nodemon] starting `node index index.js`    
internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^                                    

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import 'E:OneDriveDocumentsJWT AUTHjsonwebtnode_modulessequelizedist' is not supp orted resolving ES modules imported from E:OneDriveDocumentsJWT AUTHjsonwebtcontrollersusers.js
    at finalizeResolution (internal/modules/esm/resolve.js:272:17) 
    at moduleResolve (internal/modules/esm/resolve.js:699:10)      
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
    at Loader.resolve (internal/modules/esm/loader.js:86:40)       
    at Loader.getModuleJob (internal/modules/esm/loader.js:230:28) 
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:56:40)
    at link (internal/modules/esm/module_job.js:55:36) {
  code: 'ERR_UNSUPPORTED_DIR_IMPORT',
  url: 'file:///E:/OneDrive/Documents/JWT%20AUTH/jsonwebt/node_modules/sequelize/dist'
}

[nodemon] app crashed - waiting for file changes before starting...

This just happened, because yesterday when I used the command, it was all right.
And this is the result when I run “dir”.

PS E:OneDriveDocumentsJWT AUTH> dir

    PS E:OneDriveDocumentsJWT AUTHjsonwebt> dir
    
        Directory: E:OneDriveDocumentsJWT AUTHjsonwebt
    
    
    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    da---l        1/11/2022   2:42 PM                config
    da---l        1/11/2022   3:31 PM                controllers
    da---l        1/11/2022   3:01 PM                models
    da---l        1/11/2022   2:35 PM                node_modules
    da---l        1/11/2022   3:35 PM                routes
    -a---l        1/11/2022   5:04 PM            115 .env
    -a---l        1/13/2022   9:01 AM            448 index.js
    -a---l        1/11/2022   2:33 PM          44993 package-lock.json       
    -a---l        1/13/2022   8:44 AM            515 package.json
    -a---l        1/13/2022   8:48 AM            226 request.rest

Is there any advice that can help me? TIA^^

here’s my package.json

{
  "name": "jsonwebt",
  "version": "1.0.0",
  "description": "json web token login",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "nodemon index.js",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "rara",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.1",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "dotenv": "^11.0.0",
    "express": "^4.17.2",
    "jsonwebtoken": "^8.5.1",
    "mysql2": "^2.3.3",
    "sequelize": "^6.13.0"
  }
}

here’s my index.js

import express from "express";
import dotenv from "dotenv"
import db from "./config/database.js";
import router from "./routes/index.js";
dotenv.config();
const app = express();

try {
    await db.authenticate();
    console.log('CONGRATULATIONS!! Database Connected...');
} catch (error) {
    console.error(error);
}

app.use(express.json());
app.use(router);

app.listen(5000, () => console.log('Server Running at Port 5000'));

Javascript uncaught type error is not a function Builder Pattern

I am building a validator using a Builder Pattern. Not sure if I am using the correct pattern but I keep on having Javascript uncaught type error is not a function although my codes works.

Full Error msg:

Uncaught TypeError: validate.IsTCAgree(...).IsRMGTCAgree is not a function 
at HTMLButtonElement.<anonymous> (TPR:1846:115) 
at HTMLButtonElement.dispatch (jquery-3.5.1.js:5429:27) 
at HTMLButtonElement.elemData.handle (jquery-3.5.1.js:5233:28)
$btnSubmit.click(function(e) {
      var validate = new ValidatorTnCBuilder($btnSubmitErrMsg);
      if (validate.IsTCAgree('Please check Terms and Conditions.').IsRMGTCAgree('Please check 
          agreement.
          ')) {
          // do sth
        }
      });
    const ValidatorTnCBuilder = function($el) {
      return {
        IsTCAgree: function(msg) {
          if (!$checkIsTCAgree.is(':checked')) {
            $el.text(msg);
            return false;
          }
          return this;
        },
        IsRMGTCAgree: function(msg) {
          if (!$checkIsRMGTCAgree.is(':checked')) {
            $el.text(msg);
            return false;
          }
          return this;
        }
      }
    }

change string in multidimensional array to object depending on index prop of object within another array [duplicate]

I have two arrays. my Array1 is a multi-dimensional array of just strings.

The Array2 is an array of objects. each object has 2 key value pairs one is called “value” the other is “HeaderIndex”

If Array1 has an array with a string a index 0 I want to find the “value” key from Array2 and convert the Array1 string to a new object matching the HeaderIndex value.

I am trying to convert the multi dimensional array to another multidimensional array but instead of strings, I want it to be objects depending on index prop from Array2

const Array1 = [ 
['Alex', 'Boe', 'MeowWolf', 'pizza', 'pink'],
['Arron', 'Coe', 'Kmart', 'tofu', 'purple'],
['Jane', 'Doe', 'Sears', 'tacos', 'orange'],
['John', 'Eoe', 'YugiOh', 'blueberries', 'magenta'],
['Suzie', 'Boe', 'Toyota', 'steroids', 'blue']
]


const Array2 = [
    { value: 'First name', HeaderIndex: 0},
    { value: 'Last name', HeaderIndex: 1},
    { value: 'Company', HeaderIndex: 2},
    { value: 'Favorite food', HeaderIndex: 3},
    { value: 'Favorite color', HeaderIndex: 4},
]

I am trying to get this output below

const Finalresult = [ 
[{First name: 'Alex'}, {Last name: 'Boe'}, {company: 'MeowWolf', {Favorite food: "pizza", {Favorite color: "pink"}],

[{First name: 'Arron'}, {Last name: 'Boe'}, {company: 'Kmart', {Favorite food: "tofu", {Favorite color: "purple"}],

[{First name: 'Jane'}, {Last name: 'Doe'}, {company: 'Sears', {Favorite food: "tacos", {Favorite color: "orange"}],

[{First name: 'John'}, {Last name: 'Eoe'}, {company: 'YugiOh', {Favorite food: "blueberries", {Favorite color: "magenta"}],

]

Axios 404 error finding /api/private when not authenticating at root director

I was following a tutorial to create a user authentication – a user dashboard page is hidden and appears if the user is logged in. It works perfectly fine at the / directory but not if I change the / directory to /dashboard, even if I update all instances of "/" to "/dashboard".

Here’s my Axios code for authenticating if the user is logged in; the problem arises in /api/private, where I get a 404 error GET http://localhost:3000/api/private 404 (Not Found) ONLY when the directory for the user’s dashboard is NOT at "/".

  const fetchPrivateDate = async () => {
      const config = {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("authToken")}`,
        },
      };

      try {
        const { data } = await axios.get("/api/private", config);
        setPrivateData(data.data);
      } catch (error) {
        localStorage.removeItem("authToken");
        console.log(error);
        setError("Error");
      }
    };

    fetchPrivateDate();
  }, []);

Here is the server node.js code:

app.get("/dashboard", (req, res, next) => {
  res.send("Operational");
});

app.use("/api/auth", require("./routes/auth"));
app.use("/api/private", require("./routes/private"));

I believe the /auth path works; login and signup work completely fine, it’s just that once the user logs in the dashboard it catches an error because it can’t find api/private.

Here is routes/private aka api/private:

const express = require("express");
const router = express.Router();
const { getPrivateRoute } = require("../controllers/private");
const { protect } = require("../middleware/auth");

router.route("/dashboard").get(protect, getPrivateRoute);

module.exports = router;

I looked at plenty of other posts, such as this one: Method Post with Axios giving Error 404. ReactJS but none of the changes, such as updating the axios.get to include localhost:3000 works at all. For reference, this is the tutorial I followed: https://www.youtube.com/watch?v=YocRq-KesCM&list=LL. I’ve tried several solutions online and nothing seems to work. Any help would be greatly appreciated.

Image Tag In HTML not clicking with jQuery

I’m making a clicker game but one of my images (for an upgrade) won’t work when I click it. The problem is in the helper div image.
I’m using HTML , css, javascript and jQuery for js

Code:

var clicks = 0;
var perclick = 1;
var persec = 0;
var costup1 = 12;
var currentup1 = 0;
var costup2 = 27;
var currentup2 = 0;
setInterval(sec, 1000)
//click and upgrade
$(document).ready(function() {
  $("#sun").click(function() {
    add()
  })
  $("#up1").click(function() {
    if (clicks >= costup1) {
      clicks = clicks - costup1
      currentup1 = currentup1 + 1;
      costup1 = ((currentup1 + 1) * 12);
      perclick = perclick + 1
      update()
    } else {
      alert("You Don't Have Enough Clicks");
    }
  })
  $("#up2").click(function() {
    if (click >= currentup2) {
      clicks = clicks - costup2
      currentup2 = currentup2 + 1;
      costup2 = ((currentup2 + 1) * 27)
      persec = persec + 1;
      update()
    } else {
      alert("You Don't Have Enough Clicks")
    }
  })
  //Save and load
  $(document).ready(function() {
    $("#save").click(function() {
      localStorage.setItem("clicks", clicks)
      localStorage.setItem("perclick", perclick)
      localStorage.setItem("persec", persec)
      localStorage.setItem("currentup1", currentup1)
    })
    $("#load").click(function() {
      clicks = localStorage.getItem("clicks")
      clicks = parseInt(clicks)
      perclick = localStorage.getItem("perclick")
      perclick = parseInt(perclick)
      persec = localStorage.getItem("persec")
      persec = parseInt(persec)
      currentup1 = localStorage.getItem("currentup1")
      currentup1 = parseInt(currentup1)

    })
  })
})


function add() {
  clicks = clicks + perclick;
  update()
}

function sec() {
  clicks = clicks + persec;
  update()
}

function update() {

  document.getElementById("costmag").innerHTML = ((currentup1 + 1) * 12) + " Clicks";
  document.getElementById("curmag").innerHTML = "You Own " + currentup1 + " Magnifying Glasses(+1 Clicks Per Click)"
  document.getElementById("scoreText").innerHTML = clicks + " Clicks";
  document.getElementById("clickText").innerHTML = "You Are Gaining " + perclick + " Clicks Per Click"
  document.getElementById("secText").innerHTML = "You Are Gaining " + persec + " Clicks Per Second"

  document.getElementById("helpcur").innerHTML = "You Have " + currentup2 + " Helpers(+1 Clicks Per Second)"
  document.getElementById("helpcos").innerHTML = ((currentup2 + 1) * 27) + " Clicks";

}
img {
  -webkit-user-drag: none;
}

button {
  box-sizing: border-box;
  background-color: #000000;
  color: cyan;
  border: none;
  font-size: 16px;
}

body {
  font-family: Architects Daughter;
}

```
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Clicker Game Made With jQuery</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="script.js"></script>
  <link rel="stylesheet" href="styles.css">
</head>

<body>

  <p id="clickText"> You Are Gaining 1 Clicks Per Click </p>
  <p id="secText"> You Are Gaining 0 Clicks Per Second </p>
  <a href="javascript:;"><img src="Images/sun.png" id="sun"></a>
  <p id="scoreText">0 Clicks</p>


  <div class="magnify">
    <p id="curmag"> You Own 0 Magnifying Glasses(+1 Clicks Per Click)</p>
    <a href="javascript:;"><img src="Images/magnify-glass.png" width="50px" height="50px" id="up1"></a>
    <p id="costmag"> 12 Clicks </p>
  </div>



  <div class="helper">
    <p id="helpcur"> You Have 0 Helpers (+1 Clicks Per Second)</p>
    <a href="javascript:;"><img src="Images/helper.png" width="60px" height="80px" id="up2"></a>
    <p id="helpcos"> 27 Clicks </p>
  </div>

  <div class="svld">
    <button id="save">Save</button>
    <button id="load">Load</button>
  </div>

</body>

</html>

vjs video is not showing in Chrome and Firefox, but working in Safari

I am using a fullpage js and the site is
https://ldmm2-harmonie.netlify.app/

Here is my code for the video

  <link href="https://vjs.zencdn.net/7.17.0/video-js.css" rel="stylesheet" />
  <script src="https://vjs.zencdn.net/7.17.0/video.min.js"></script>
  <link href="https://unpkg.com/@videojs/[email protected]/dist/sea/index.css" rel="stylesheet"/>
  <script src="js/jquery-3.1.1.min.js"></script>
        <div class="container">
           <div id="videoSectionCarousel" class="carousel slide" data-interval="false">
              <video id="example_video_1"  class="video-js vjs-fluid vjs-nofull vjs-theme-sea" controls preload="auto" width="800" height="521" playsinline="playsinline" poster="img/video_poster_523.jpg" data-setup="{}">
                 <!-- poster="img/dummy-video-img.jpeg" -->
                 <source src="https://ldmm2-harmonie.netlify.app/img/videoSection/sales-video.mp4" type="video/mp4">
                 <source src="http://vjs.zencdn.net/v/oceans.ogv" type="video/ogg">
                 <p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>
              </video>
           </div>
        </div>

For some reason it is not showing anymore. It works in Safari….

Is there a way I can manually update client side contents after sign-up

I’m a front end dev on my way to backend and this is a personal project. It was meant to be static so all users see the same information on their page but now I want to be able to change some details based on the clients who signs up. For example. All users were meant to see a $20 bill for a community project but now I want to be able to increase or decrease that amount on different client user page.