how can I find documents that aren’t referenced by a document from another collection

I have two models called session and unreadcount. I need to get that particular session count from another table. below are my two Mongodb models.

var UnreadCountSchema = new mongoose.Schema({
    userId: { type: String, required: true },
    sessionId: { type: String, required: true},
    unreadCount: { type: Number, required: true, default: 0  },
    isDeleted: { type: Boolean, required: true, default: 0 },
}, { timestamps: true });

module.exports = mongoose.model("UnreadCount", UnreadCountSchema);

var SessionSchema = new mongoose.Schema({
    name: { type: String, required: false },
    subject: { type: String, required: false },
    sessionCode: { type: String, required: false },
}, { timestamps: true });
module.exports = mongoose.model("Session", SessionSchema);

I have not used referencing and relation. I need to get a count when I fetch the session. I have tried lookup it doesn’t work. suggest me a way to do this

The following is my code that i executed. count is there but iam not getting the result.

const response = await SessionModel.aggregate([
            {
                $match: query,
            },
            {
                $lookup: {
                    from: "UnreadCount",
                    localField: "_id",
                    foreignField: "sessionId",
                    as: "unreadCounts",
                },
            },
            {
                $addFields: {
                    unreadCount: {
                        $cond: {
                            if: { $gt: [{ $size: "$unreadCounts" }, 0] },
                            then: { $arrayElemAt: ["$unreadCounts.unreadCount", 0] },
                            else: 0,
                        },
                    },
                },
            },
            // Optionally sort the sessions by lastMessage createdAt
            // { $sort: { "lastMessage.createdAt": -1 } },
        ])

Route.get() requires a callback function but got object string

I have gone through the other similar posts but not sure or experienced enough to relate the resolution suggestions on my project.
I have created a simple app with two main routes as part of my learning through a udemy course, however, i cannot get around this issue of Error: Route.get() requires a callback function but got a [object String]. I know that that main aim is to export the router object containing all the nested routes for a root route but the fact that the error is asking for a callback doesn’t make sense to me. Also the source of the error is the route.js file in the main node_modules library, node_modulesexpresslibrouterroute.js:211:15.

Tried a new test controller, same issue when running that file even without importing any of the route files. Deleted the route.js file from the library, new error shows up, Error: Cannot find module ‘./route’. Officially stuck.

Insights and suggestions would be absolutely appreciated .
I have added the route, controller and package.json files below for reference.

controller (app.js)

const express = require('express');
const ejs = require('ejs');
const Joi = require('joi');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const flash = require('connect-flash');
const session = require('express-session');
const path = require('path');
const ejsMate = require('ejs-mate');
const app = express();

mongoose.connect('mongodb://127.0.0.1:27017/yelp-camp-new')
    .then(
        console.log('Connected to YelpCamp New db')
    )
    .catch(e => {
        console.log('error');
        console.log(e);
    }
    );

app.get('view engine', 'ejs')
app.engine('ejs', ejsMate);
app.set('views', path.join(__dirname, '/views'));
app.use(express.json()) // parse json api data
app.use(express.urlencoded(({ extended: true }))); // parse form data encoded in body
app.use(methodOverride('_method')); // method over-ride for post requests


//Session and flash
const sessionConfig = { 
    secret: 'Thi$i$m7secret',
resave: false, 
saveUninitialized: false,
cookie:{
   httpOnly: true, // extra layer of security
   _expires: Date.now() + 1000 *60*60*24*7,
   maxAge: 1000*60*60*24*7
}
};
app.use(session(sessionConfig));
app.use(flash()); // flash middleware


// Serving Static files from public dir, like js and css files.
app.use(express.static(path.join(__dirname, '/public')));

// importing the routes
const campRoute = require('./routes/campRoutes');
app.use('/campgrounds', campRoute);


// =========================
// error middleware
app.use((err, req, res, next) => {
    const {message = 'Something went wrong.', status = 500} = err;
    res.status(status);
    res.render('error', {err, status})
    next(err);
})


// middleware for all the other routes not defined in this app
app.use('*', (req, res) =>{
    res.send('This page does not exist')
})

app.listen(3000, ()=>{
    console.log('Listening on port 3000')
})

//==================================================================================================
route file (campRoutes.js)

const express = require('express');
const router = express.Router();

// pott.get('/', async (req, res)=>{
//    const camps = await Campground.find({});
//    res.render('showAllCamps', {camps});

// });


router.get('/new', (req, res)=>{
    res.render('new');
});

router.post('/', async(req, res)=>{
    const {campground} = req.body;
    console.log(campground);
})

module.exports = router;

//==================================================================================================

package.json file

{
  "name": "yelpcamp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {

    "connect-flash": "^0.1.1",
    "ejs": "^3.1.9",
    "ejs-mate": "^4.0.0",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "joi": "^17.11.0",
    "method-override": "^3.0.0",
    "mongoose": "^8.0.1"
  }
}

Custom Css on Theme APEX 23.1 won’t apply

I’ve added a custom css on my theme for JSON Configuration section of theme.
and Here’s what I do :

 {"customCSS":"",
"vars":{"@g_Accent-BG":"#505f6d",
"@g_Accent-OG":"#ececec",
"@g_Body-Title-BG":"#dee1e4",
"@l_Link-Base":"#337ac0",
"@g_Body-BG":"#f5f5f5"}}

But some of color like #505f6d won’t apply at all . Where did I go wrong ?

scrollIntoView go to section instantly

I was trying to make a simple full page scroll effect with the scrollIntoView method. But it just jump to the section instantly instead of ‘smooth scrolling’ although I have already set this in the option behavior: "smooth".

I’m using the latest version of Edge, I have also tested on Firefox, both are not working. The reason why I test on different browser is because I have try Google relevant tutorial, weirdly their example are not working too, so I wonder is it my code is wrong or something is wrong with my browser or laptop:

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_element_scrollintoview
https://www.javascripttutorial.net/javascript-dom/javascript-scrollintoview/

Watch my record: https://streamable.com/xbfh31

Below is the minimal code that you can test:

document.addEventListener("DOMContentLoaded", () => {
  const sections = document.querySelectorAll(".section");
  let currentSection = 0;

  function scrollToSection(index) {
    sections[index].scrollIntoView({ behavior: "smooth" });
    currentSection = index;
  }

  // Mouse Wheel Event
  document.addEventListener("wheel", (event) => {
    if (event.deltaY > 0 && currentSection < sections.length - 1) {
      scrollToSection(currentSection + 1);
    } else if (event.deltaY < 0 && currentSection > 0) {
      scrollToSection(currentSection - 1);
    }
  });

  // Touch Events for Mobile Devices
  let touchStartY = 0;
  let touchEndY = 0;

  document.addEventListener("touchstart", (event) => {
    touchStartY = event.touches[0].clientY;
  });

  document.addEventListener("touchend", (event) => {
    touchEndY = event.changedTouches[0].clientY;

    const deltaY = touchEndY - touchStartY;

    if (deltaY > 0 && currentSection > 0) {
      scrollToSection(currentSection - 1);
    } else if (deltaY < 0 && currentSection < sections.length - 1) {
      scrollToSection(currentSection + 1);
    }
  });
});
body,
html {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
}

.section {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2em;
}

#section1 {
  background-color: blue;
}

#section2 {
  background-color: green;
}

#section3 {
  background-color: gray;
}
<div id="section1" class="section">
  <h2>Section 1</h2>
</div>
<div id="section2" class="section">
  <h2>Section 2</h2>
</div>
<div id="section3" class="section">
  <h2>Section 3</h2>
</div>

How can I iterate over anchors assigned to JavaScript functions in Selenium using python?

I am working on a web scraping project using Selenium in Python. I have successfully scraped a set of anchors from a website, and I want to iterate over these anchors, click each link, run some code to extract data from the webpage, and then move to the next anchor in the set.

The anchors I’m working with look like this:

    <a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$GridView1','Page$2')">2</a>
    <a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$GridView1','Page$3')">3</a>

I have stored these anchors in a variable as follows:

    anchors = d.find_elements(By.XPATH, '//*[@id="ContentPlaceHolder1_GridView1"]/tbody/tr/td/table/tbody/tr/td/a')

When I attempt to iterate over the anchors and click each link, I encounter a StaleElementReferenceException. Here’s a simplified version of my code:

    i = 0
    for a in anchors:
        anchors[i].click()
        *Code to extract data from the webpage*
        i += 1

I have tried various versions of this code, including more robust solutions found in other Stack Overflow threads, but the issue persists. The error message I receive is:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found

I have checked that the table containing the anchors and the anchors themselves do not change when navigating between pages. The XPaths for both remain the same.

I have referred to the following Stack Overflow threads without success:

Fetch all href link using selenium in python
Selenium: Iterating through groups of elements

I would greatly appreciate any guidance or solutions to resolve this issue. Thank you in advance.

hey guys, How can I get an auto incrementing ID that is created when sending data via AJAX and PHP?

I want the buyer_id data to display through SQL on another page. This is how I try to get it from the other page

 
<?php
include(“bd_con.php”);
$buyer-id= $_GET[‘buyer-id’];

       echo "<script>                  alert('$buyer_id')</script>";

    $query = "SELECT name, email,               city, province, identification, address, 

          extra-details, image, title, description, id_type FROM `purchased_property` inner join 

property ON purchased_property.property-id = property.id WHERE buyer-id=’$buyer-id'”;

            $linking = mysqli_query($bd_con, $query);

              $info = mysqli_fetch_assoc($linking);

?>
 
this is the form from the page I send data through AJAX
 

                <div class="form">
                    <h2>Personal data</h2>
                   <input type="text"    placeholder="Full name" id="full_name"
        name="full_name"></input>
                   <label>Date of birth</. label>
                  <input type="date"     id="date_birth" name="date_birth">
                  <div   id="paypal-button-container"></div>
       
               </div>
              </form>

 

Just as I showed you up guys, I tried by $_GET but didn’t work. I hope you can help me:)

Delay in Updated Metadata Reflection on SEO Engines and Social Media Platforms: Seeking Insights on Timelines and Expedited Updates [migrated]

Hello Stack Overflow community,

Despite correctly implementing metadata tags within my web application, I’ve noticed a delay in their reflection on SEO engines and social media platforms like Facebook. The meta tags appear accurately when inspected within the section of the HTML. I’ve employed a code snippet that updates meta tags using the setMetaTags function triggered by the useEffect hook when currentPost is available. However, I’m curious about the time it takes for these changes to take effect in search engine results and platform previews. Any insights or estimated durations for when these platforms typically update their indexes and caches after metadata changes are made would be greatly appreciated. Below is the snippet of code used to update the meta tags:

useEffect(() => {
    if (currentPost) {
        setMetaTags();
    }
}, [currentPost]);

const setMetaTags = () => {
    if (typeof window !== 'undefined') {
        document.title = currentPost.title;

        // Setting description meta tag
        const descriptionMeta = document.querySelector(
            'meta[name="description"]'
        );
        if (descriptionMeta) {
            descriptionMeta.setAttribute(
                'content',
                currentPost.shortdescription
            );
        } else {
            const newDescriptionMeta = document.createElement('meta');
            newDescriptionMeta.setAttribute('name', 'description');
            newDescriptionMeta.setAttribute(
                'content',
                currentPost.description
            );
            document.head.appendChild(newDescriptionMeta);
        }

        // Setting image meta tag
        const imageMeta = document.querySelector(
            'meta[property="og:image"]'
        );
        if (imageMeta) {
            imageMeta.setAttribute('content', currentPost.image);
        } else {
            const newImageMeta = document.createElement('meta');
            newImageMeta.setAttribute('property', 'og:image');
            newImageMeta.setAttribute('content', currentPost.image);
            document.head.appendChild(newImageMeta);
        }
    }
};

Thank you in advance!

Make selected element stay at one place while scrolling the neighbouring elements in a carousel like setting

I’m trying to create a lightbox,

I have a thumbnail carousel at the bottom of the images that you click on to change the displayed image. I want to make it so that when you click on any thumbnail, it scrolls to the center of the page making it seem like the selected element remains constantly at the center of the screen.

What I’ve done till now is I’ve added a dynamic left padding to the ThumbnailViewer container.

const ThumbnailViewer = (props) => {
const {
    images = [],
    currentImage = 0,
    thumbnailWidth
} = useContext(LightboxContext);

const getThumbnailViewerPaddingLeft = () => {
    if (thumbnailWidth) {
        return `calc(95vw - ${(thumbnailWidth * (currentImage + 1))}px)`
    }

}
const getThumbnailViewerPaddingRight = () => {
    if (thumbnailWidth) {
        return `calc(95vw - ${thumbnailWidth}px)`
    }

}

return (
    <div className={styles.thumbnailViewer} style={{ paddingLeft: getThumbnailViewerPaddingLeft() }}>
        {images.map((el, i) => <ThumbnailIcon img={el.src} alt={el.alt} selected={i == currentImage} current={i} />)}
    </div>
)

}

I’m unable to get it centred as you can see in this gif below and I’m not sure if this approach is right. I’m thinking to dynamically reduce left padding and then add right padding to it constantly so that when clicking on the right most element it gets to the center too.

enter image description here

Can someone help me if I’m on the right path or there is a better way to do this?

SCEditor: Dropdown is out of place

When I create the sceditor like in the example, the dropdowns that appear when clicking on the font icon appears in its normal place.

        var textarea = document.getElementById('example');
        sceditor.create(textarea, {
            format: 'bbcode',
            icons: 'monocons',
            autofocus: true,
            style: '../minified/themes/content/default.min.css'
        });

However, once I specify my own toolbar, the dropdown is moved off screen and I have to scroll down for ages to find it.

        var textarea = document.getElementById('example');
        sceditor.create(textarea, {
            format: 'bbcode',
            icons: 'monocons',
            autofocus: true,
            style: '../minified/themes/content/default.min.css',
            toolbarContainer: document.getElementById('toolbar')
        });

Any way to correct the positioning while having a custom toolbar?

Cannot use import statement outside a module (Vanilla JS)

I’m getting Cannot use import statement outside a module(Vanilla Javascript) while testing a simple demo app locally using nano server.

data.js

const data = {
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
}

export {data};

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Supercluster Leaflet demo</title>

        <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
        <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>

        <link rel="stylesheet" href="cluster.css" />

        <style>
            html, body, #map {
                height: 100%;
                margin: 0;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
        <script type="module" src="data.js"></script>
        <script src="index.js"></script>
    </body>
</html>

index.js

import {data} from 'data.js';

/*global L */

// The rest not needed

JavaScript Embedding and Extraction in PDFs

I want to embed some JS code into a pdf that extracts the content of a line and auto runs on open.
I tested it out by just running app.alert and it worked on MSEdge.

What JS Modules/methods would I have to use to achieve this. Any answer helps

I have tried finding modules online and the ones I have found are all working from the outside, asking for file name. I am looking for JS code that I want to embed into my PDF that extracts the content of backend line 57 and runs app.alert(line 57)

Javascript callbacks fundamentals from C# point of view

Please help me understand two thing about callbacks. They are the last JS weirdness left for me that I can’t grasp having strong C# background.

First – why should we send function as parameters. I know that we can, but why. I will try the simplest example I can think of. So according to the JS developers it should be like this:

function simpleCallbackFn (){}

function simpleCallerFn (cb){ cb();}

simpleCallerFn (simpleCallbackFn);

Why not like this:

function simpleCallbackFn (){} // Same as before

function simpleCallerFn (){ simpleCallbackFn ();}  

We do not pass a callback, we simply call it from within the caller. It is within perfectly visible scope. Then we just make the initial call.

simpleCallerFn ();

Calling the “callback” function from within the caller function to me should be perfectly fine and achieve the same result.

Second – say I need to use callback with arguments

function simpleCallbackFn (anArgument){}

function simpleCallerFn (cb){ 
   cb(anArgument);
}

We know that this will not work
simpleCallerFn (simpleCallbackFn(anArgument));

According to the JS developers it should be like this:

simpleCallerFn (() => simpleCallbackFn(anArgument));

I am thinking why not:

function simpleCallbackFn (anArgument){}

function simpleCallerFn (anArgument, cb){ 
   cb(anArgument);
}

Then make the initial call like this:

simpleCallerFn (anArgument, simpleCallbackFn);

Please. That Javascript makes me fell like in freak’s circus.

Thank you.

Is there a way to make the balls generate at random positions within the canvas?

function setup()
{
 createCanvas(800, 600);

//other code has been omitted
}

function generateRandomBalls() {

    var numRows = 5; // we have 4 rows, 5 including the top row
    var radius = 8;
    var startX = Math.random();
    var startY = Math.random();

    for (var row = 0; row < numRows; row++) {
        for (var i = 0; i <= row; i++) {
            var xOffset = row * (sqrt(3) * radius);
            var yOffset = row * (radius * 3) / 2;
            var x = startX + xOffset;
            var y = startY - i * (radius * 3) + yOffset;

            var ball = Bodies.circle(x, y, 11, {
                restitution: 1,
                friction: 0.5,
                render: { fillStyle: 'red' }, // we set the color of the ball to red
                velocity: { x: 1, y: 2 },
                //collisionFilter: { group: 0x0002 }
            });
            Body.setAngle(ball, PI / 2); // we change the angle from -PI/2 to PI/2 to flip the triangle
            balls.push(ball);
        }
    }

    
    World.add(engine.world, balls);
}

The code should make the positions of the red balls are within the canvas at random but always remain with a grid-style (triangle style) shape, so that every time the game starts, it start at a random position of the canvas.