Hide HTML element using JQuery

I would like to hide an element based on a role. (The roles are “Teacher” and “Student”)
This is the element I want to hide if a role is Student.

tab.html

<a href="/profile" class="nav-item nav-link">Update</a>

<script src="{{ url_for('jquery', filename='jquery/profile/tab.js') }}"></script> //to access the .js file

I like to create a function in tab.js that will hide the element above if the role is “Student” but I do not have that much idea since I have no experience with JQuery

How to group JavaScript Object in javascript

seek for help for grouping them. I got an input with this.

[
{
“apiName”: “APISend”,
“channel”: “Mozilla”,
“noa”: 3
},
{
“apiName”: “API”,
“channel”: “PostMan”,
“noa”: 1
},
{
“apiName”: “APICall”,
“channel”: “PostMan”,
“noa”: 4
},
{
“apiName”: “API”,
“channel”: “Mozilla”,
“noa”: 2
}
]

How can I group them as channel and then by apiName? My final output should be like this:

labels = [“Mozilla”,”PostMan”]

datasets = [{label:”APISend”, data:[3,0]} , {label:”API”,data:[2,1], {label:”APICall”,data:[0,4]]}

How to use dynamic import from a dependency in Node.js?

I’m using Node.js (v16) dynamic imports in a project to load plugins using a function loadJsPlugin shown here:

import { pathToFileURL } from 'url';

async function loadJsPlugin(pluginPath) {
  const pluginURL = pathToFileURL(pluginPath).toString();
  const result = await import(pluginURL);
  return result.default;
}

My main program provides absolute paths to the loadJsPlugin function, such as /home/sparky/example/plugins/plugin1.js (Linux) or C:Userssparkyexamplepluginsplugin1.js (Windows). The pathToFileURL function then converts these absolute paths to URLs like file:///home/sparky/example/plugins/plugin1.js (Linux) or file:///C:/Users/sparky/example/plugins/plugin1.js (Windows).

Loading the plugins this way works fine when the loadJsPlugin function is in the same package as the main program, like this:

import { loadJsPlugin } from './plugin-loader.js';

async function doSomething() {
  const plugin = await loadJsPlugin('...'); // works
  // use plugin
}

However, if I try to move loadJsPlugin to a separate library and use it from there, it fails with Error: Cannot find module '<url here>'

import { loadJsPlugin } from '@example/plugin-loader';

async function doSomething() {
  const plugin = await loadJsPlugin('...'); // error
  // use plugin
}

NOTE: the dependency name here is not on NPM, it’s on a private repository and there’s no problem loading the dependency itself. Also, static ES6 imports in general are working fine in this system.

I looked through Node.js documentation, MDN documentation, and other StackOverflow questions for information about what is allowed or not, or whether dynamic import works differently when in the same package or a dependency, and didn’t find anything about this. As far as I can tell, if a relative path or file URL is provided, and the file is found, it should work.

Ruling out file not found:

  1. I can switch back and forth between the two import lines to load the loadJsPlugin function from either ./plugin-loader.js or @example/plugin-loader, give it the same input, and the one in the same package works while the one from the dependency doesn’t.

  2. When I test in VS Code, I can hover the mouse over the URL in the Error: Cannot find module 'file:///...' message and the file opens just fine

  3. I can also copy the ‘file:///…’ URL to a curl command (Linux) or paste it into the address bar of Windows Explorer and it works.

  4. If I try a path that actually doesn’t exist, I get a slightly different message Error [ERR_MODULE_NOT_FOUND]: Cannot find module '<path here>', and it shows the absolute path to the file that wasn’t found instead of the file URL I provided.

Checking different file locations:

  1. I tried loading plugins that are located in a directory outside the program (the paths shown above like /home/sparky/example/plugins/...); got the results described above

  2. I tried loading plugins that are located in the same directory (or subdirectory) as the main program; same result

  3. I tried loading plugins that are packaged with the dependency in node_modules/@example/plugin-loader; same result (obviously this is not a useful set up but I just wanted to check it)

I’d like to put the plugin loader in a separate library instead of having the same code in every project, but it seems that dynamic import only works from the main package and not from its dependencies.

I’m hoping someone here can explain what is going on, or give me a pointer to what might make this work.

javascript append at specific index document.querySelector

I am trying to create a new element and insert it inside document.querySelector(‘.content’); at specific index? my simple code below.

const container = document.querySelector('.content');
var counter = 0;
var p = document.createElement('p');
p.textContent = "INSERT NEW"
var buttonOne = document.createElement('button');
buttonOne.className = "btnClass";
buttonOne.innerText = "Insert";
buttonOne.onclick =  function() {
    var buttonTwo = document.createElement('button');
    buttonTwo.className = "btnClass";
    buttonTwo.innerText = "new";
    var nodes = Array.prototype.slice.call(document.getElementById('container').children);
    var index = nodes.indexOf(this);
    var c = document.createElement('p');
    c.textContent = "inserted new p";
    **container.append(c, buttonTwo, index++); <-- something like this**
};

for (let i = 0; i < 5; i++) {
    var p = document.createElement('p');
    p.textContent = "Index" + " " + i 
    container.append(p, buttonOne);
}

for example; if I have 10 buttons. Click on the 3rd, it should ADD a new element at 4th and pushes the rest.
is it possible? or any other options?

TypeError: user.setNickname is not a function

so I have just finished this /setnick command for my Discord Bot, but I am getting the following error.

TypeError: user.setNickname is not a function
    at Object.execute (/Users/Aplex/Downloads/Aplel-Bot/Commands/Moderation/setnick.js:43:24)
    at Object.execute (/Users/Aplex/Downloads/Aplel-Bot/Events/Interaction/interactionCreate.js:24:15)
    at Client.<anonymous> (/Users/Aplex/Downloads/Aplel-Bot/Structures/Handlers/Events.js:17:50)
    at Client.emit (node:events:402:35)
    at InteractionCreateAction.handle (/Users/Aplex/Downloads/Aplel-Bot/node_modules/discord.js/src/client/actions/InteractionCreate.js:74:12)
    at Object.module.exports [as INTERACTION_CREATE] (/Users/Aplex/Downloads/Aplel-Bot/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (/Users/Aplex/Downloads/Aplel-Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
    at WebSocketShard.onPacket (/Users/Aplex/Downloads/Aplel-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/Users/Aplex/Downloads/Aplel-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/Users/Aplex/Downloads/Aplel-Bot/node_modules/ws/lib/event-target.js:199:18)

I have tried looking for solutions on google and here on StackOverflow but I couldn’t find any regarding my problem. Does anyone know what the fix for this is?

Here is the /setnick command file:

const { Client, Interaction, MessageEmbed } = require("discord.js");

module.exports = {
    name: "setnick",
    description: "Sets nicname to a user.",
    options: [
        {
            name: "user",
            description: "User to change nickname",
            type: 6,
            required: true
        },
        {
            name: "nickname",
            description: "New nickname",
            type: 3,
            required: true,
        },
    ],
    /**
     * 
     * @param {Interaction} interaction 
     * @param {Client} client 
     */
    async execute(interaction, client) {
        try {
            const { options } = interaction;
            const args = options._hoistedOptions;

            const user = args.find(x => x.name == "user");
            const nickname = args.find(x => x.name == "nickname");

            const embed = new MessageEmbed()
            .setColor("RED")

            if(!user.member.manageable) {
                embed.setDescription(`:x: I can't change ${user.member.toString()}'s Nickname`)
                return interaction.reply({embeds: })
            }

            const oldNick = user.member.nickname ? user.member.nickname : user.member.user.username;

            await user.setNickname(nickname.value);

            embed.setDescription(`:white_check_mark: ${user.member.toString()}'s nickname changed!`).setFooter(`From ${oldNick} to ${nickname.value}`);

            await interaction.reply({embeds: });
        } catch (err) {
            console.log("Something went wrong => ", err);
        }
    },
};

Seek Pagination with Knex library for Postgress

Attempting to implement cursor based pagination – and I would like to know the proper way to call it with Knex for Postgres.

Here is the standard statement:

SELECT 
FROM 
WHERE (timestamp, id) > (cursor.age, cursor.id)
ORDER BY timestamp ASC, id ASC
LIMIT

And my attempt with Knex:

const knexResult = await knex({ 'table_name' })
    .select(columns)
    .where('created_at', '>', cursor.timestamp)
    .andWhere('id', '>', cursor.id)
    .orderBy(['timestamp', 'id'])
    .limit(first)
  return knexResult;

Is this the proper way to call it – it seems not correct…

Explicitly Close Dropdown Menu in Vue.js

I have a drop down menu in a Vue application which I need to explicitly close after applying some logic.

Essentially the flow is:

  1. Page loads, user clicks on a name from the drop down – name value gets written to database
  2. User reloads page, clicks on a different name, gets a pop-up asking if they want to save the new name

At this point, if the user confirms their choice, the new name gets written to the database, but the drop down stays open.
I need to add some logic to call after the user confirms their choice in step 2 to ensure that the drop down doesn’t stay open.

<div class="part">
        <span class="for-label"> Employee: </span>
        <el-select v-model="dataValue.assignedUser" filterable :disabled="notClick" @change="handle">
          <el-option
            v-for="(user, userIndex) in assignedOption"
            :key="userIndex"
            :label="user.userName"
            :value="user.userEmail"
          />
        </el-select>
      </div>

If relevant this bug only started occurring after adding the “filterable” attribute to the el-select.

React Native – Flatlist error when removing an item

I am using flatlist to display a list of items from async storage. I am currently getting the list of items from async storage and then displaying it using flatlist so removing an item item from the flatlist also removes it from the async storage.

The list of items (ItemsArray) consists of id and product retrieved from async storage.

When i try to remove a single item from the list i get an error as shown here:
Error 1
Error 2

Error 1 happens because the items are being compared so it can sort the list in ascending order and when the item is removed, there is no item to be compared with so it returns null.

Error 2 happens when i remove the last item from the list and i believe the error is related to the key extractor.

Async Storage: https://react-native-async-storage.github.io/async-storage/docs/api#removeitem

Code:

const [ItemArray, setItemsArray] = useState([]);
const removeItem = async (ID) => {
  await AsyncStorage.removeItem(ID);
};
const getItem = async (x) => {
  const item = await AsyncStorage.getItem(x);
  return item
};

const getAllItems = async () => {
  let temp = [];
  temp = await AsyncStorage.getAllKeys();
  const tempItems = [];
  for (let i = 0; i < temp.length; i++) {
    tempItems.push(await getItem(temp[i]));
  }
  setItemsArray(tempItems);
};
//...
return (
  <View>
    <FlatList
      data={itemsArray.sort((a, b) => (a.id > b.id ? 1 : -1))}
      renderItem={renderItem}
      keyExtractor={(product) => product.id}
    />
  </View>
);

Flattening 2D grid of 2D arrays into a single 2D array, in JavaScript (functionally)

I have a 2D array (grid) of 2D arrays (chunks) for a game I’m developing:

const c1 = [[1, 2],
            [3, 4]]

const c2 = [[5, 6],
            [7, 8]]

const c3 = [[9, 0],
            [1, 2]]

const c4 = [[3, 4],
            [5, 6]]

const grid_of_chunks = [[c1, c2],
                        [c3, c4]];

and I want to reduce/flatten the grid_of_chunks to:

[[1, 2, 5, 6],
 [3, 4, 7, 8],
 [9, 0, 3, 4],
 [1, 2, 5, 6]]

I’ve been able to implement a functional solution for this (in 2 lines of Clojure), but I’m struggling to wrap my head around translating it to functional JavaScript, and bridging the gap between the two language’s map semantics (JS map only accepts one array, whereas Clojure’s map accepts many collections…).

This is as far as I got:

function join_grid_of_chunks(gofc) {
    const joined_horiz = gofc.map(
        gofc_row => [].map.apply(gofc_row, [cs => [].concat.apply(cs)])
    );
    return [].concat.apply(joined_horiz);
}

How to build a meme javascript? [closed]

I can`t find a way to take the informations i need ,from a wordpress website, and copy them into my website.

For example:

I need to copy a list of 40 products from Apple website to my personal website

These 40 products must be copied with the price and picture of each product separately

register the id of a dropdown array in PHP Laravel 8 livewire with components?

Using Laravel 8 + Livewire: can’t record id of many drop down list in component
[my form blade][1]

<form class="form-horizontal" wire:submit.prevent="storePrecio">
        @csrf
        @foreach ($product->attributeValues->unique('product_attribute_id') as $av)
        <div class="form-group">
          <label class="col-md-4 control-label">{{ $av->productAttribute->name }} :</label>
            <div class="col-md-4">
              <select class="form-control" style="width: 200px;" wire:model="combination">
              @foreach ($av->productAttribute->attributeValues->where('product_id', $product->id) as $pav)
               <option value="{{ $pav->id }}">{{ $pav->value }}</option>
              @endforeach
              </select>
           </div>
      </div>

@endforeach

[1]: https://i.stack.imgur.com/5C0wO.jpg

Move a dynamic number of array elements from one collection’s array to another collection’s array in MongoDB

I’m working on a Discord Bot but this question is about the service-end I’ve created for the bot. The scenario I’m working on is as follows, whenever a user deletes their account all of the images uploaded by said user will be removed from the GUILDS collection and placed in the DELETED_CONTENT collection. Specifically, a user’s image data will be removed from a GUILD’s image_pool array and placed in a respective DELETED_CONTENT image_pool array.

The number of images varies by user and the number of GUILDS that a user is associated also varies. image_pool data is dynamic so overwriting that would be nuanced to maintain state, whereas the rest of a GUILD’s data is static.
What I’m looking to achieve below assuming ‘jeskoston’ deletes account. I’ve added a comment to their username for clarity.

Current GUILDS (collection)

{
    "_id" : ObjectId("61b3db8b965d8d06da643edd"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "image_pool" : [ 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbff67"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- WILL DELETE ACCOUNT", 
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Jordan",
            "image_url" : "/uploads/925819329911062589/1642820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }, 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe88"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "uploaded_by_discord_username" : "andydiscord",
            "uploaded_by_id" : "619dadc90565852231771649",
            "image_title" : "Pippen",
            "image_url" : "/uploads/825519329911062589/5442820844573IMG-1111.png",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17123"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "image_pool" : [
      {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe90"),
            "date_uploaded" : "2022-01-21T19:09:30-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- WILL DELETE ACCOUNT",
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Malone",
            "image_url" : "/uploads/995519329911062100/7842820844573IMG-4000.jpg",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
     ],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

Current DELETED_CONTENT (collection):

{
    "_id" : ObjectId("88b3db8b965d8d06da643p09"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "guild_uninstalled": false,
    "image_pool" : [ 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfk3p"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "date_deleted" : "2022-01-25T01:07:45-08:00",
            "uploaded_by_discord_username" : "andrewdiscord",
            "uploaded_by_id" : "619dadc90565852231771659",
            "image_title" : "Rodman",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,
            "date_deleted" : "2022-01-22T19:09:25-08:00",
        },
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17789"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "guild_uninstalled": false,
    "image_pool":[{
            "_id" : ObjectId("888b74edaa9c4c0f53cbff45"),
            "date_uploaded" : "2022-02-23T12:07:11-08:00",
            "date_deleted" : "2022-02-24T11:02:01-08:00",
            "uploaded_by_discord_username" : "jakediscord",
            "uploaded_by_id" : "619dadc9056585223175461f",
            "image_title" : "Stockton",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,
            "date_deleted" : "2022-03-22T04:09:00-08:00",
        }
],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

Desired GUILDS (collection) after user jeskoston deletes their account:

{
    "_id" : ObjectId("61b3db8b965d8d06da643edd"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "image_pool" : [  
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe88"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "uploaded_by_discord_username" : "andydiscord",
            "uploaded_by_id" : "619dadc90565852231771649",
            "image_title" : "Pippen",
            "image_url" : "/uploads/825519329911062589/5442820844573IMG-1111.png",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17123"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "image_pool" : [],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

Desired DELETED_CONTENT (collection) after user jeskoston deletes their account:

{
    "_id" : ObjectId("88b3db8b965d8d06da643p09"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "guild_uninstalled": false,
    "image_pool" : [ 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbff67"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "date_deleted" : "2022-01-22T19:09:25-08:00",
            "uploaded_by_discord_username" : "andrewdiscord",
            "uploaded_by_id" : "619dadc90565852231771659",
            "image_title" : "Rodman",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,

        },
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbff67"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "date_deleted" : "2022-01-26T07:09:51-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- ACCT DELETED", 
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Jordan",
            "image_url" : "/uploads/925819329911062589/1642820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17789"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "guild_uninstalled": false,
    "image_pool":[{
            "_id" : ObjectId("888b74edaa9c4c0f53cbff45"),
            "date_uploaded" : "2022-02-21T15:07:11-08:00",
            "date_deleted" : "2022-03-02T04:09:00-08:00",
            "uploaded_by_discord_username" : "jakediscord",
            "uploaded_by_id" : "619dadc9056585223175461f",
            "image_title" : "Stockton",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,
            
        },
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe90"),
            "date_uploaded" : "2022-01-21T19:09:30-08:00",
            "date_deleted" : "2022-23-22T04:09:00-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- ACCT DELETED", 
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Malone",
            "image_url" : "/uploads/995519329911062100/7842820844573IMG-4000.jpg",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

My strategy thus far has been to #1 pull a user’s images from the GUILDS collection but before doing that #2 copy data to push to the DELETED_CONTENT collection.

I have #1 finished

For #2 I have a query that collects a user’s image data and adds a date_deleted timestamp to each image. I also include other GUILD data in query. I only return guild entries where a user has images posted.

('GUILDS').aggregate([
   {

           $project:
          {    
               discord:1,
               install_date:1,
               installed_by_id:1,
               installed_by_username:1,
               preferred_locale:1,
               nsfw:1,
               guild_deleted:1,
             
               user_images:
               {
                   $filter:
                   {
                       input:"$image_pool",
                       as: "image",                             
                       cond:{ $eq: ["$$image.uploaded_by_id",'619dadc90565852231771659'] }
                   }
               }
           }
       },
           {
       $addFields: {
           guild_deleted:false,
           "user_images":{
               $map:{
                   input: "$user_images",
                    as:"image",
                    in:{
                       _id:"$$image._id",
                       date_deleted: "$$NOW",
                       date_uploaded:"$$image.date_uploaded",
                      uploaded_by_discord_username:"$$image.uploaded_by_discord_username",
                       uploaded_by_id:"$$image.uploaded_by_id",
                       image_title:"$$image.image_title",
                       image_url:"$$image.image_url",
                       likes:"$$image.likes",
                        flags:"$$image.flags",
                        nsfw:"$$image.nsfw"
                       }
               }
           }
       }
   },
       {
           $match:{ 'user_images.0':{ $exists: true }    }
       }  
])

I retrieve user data based on an images ‘uploaded_by_id’ value. I include static guild info in the event I have to upsert the whole document, user_images are a user’s images from a GUILD’s respective image_pool(s).

I want to be able to move this data without looping calls to the database. I’ve tried to use bulkWrite but have had no luck, I cannot find a concrete example that has a use-case for a dynamic number of entries. I’ve attempted to create a dynamic string for bulkWrite with no luck. I’ve also attempted to use $merge but I’m having trouble with the pipeline operators under whenMatched field.

Maybe my entire approach is off? I will spare my other attempts since this has gotten long. I’m not sure if anyone can help, but any attempt would be appreciated.

Next.js SSR with API not building properly

“Not building properly” meaning “not finishing building at all”. I’ve set up a very basic blog project with dynamic SSR which fetches data from the Notion-API to generate static blog pages. Everything works fine when I’m running it in next dev – however when trying to build the project, it runs into an endless loop without any errors shown.

One thought I had was the following:
If I understand the sequence of everything correctly, Next.js already tries building the static sites during next build. The dynamic site generation relies on an API that I have also coded within the same project, which forwards requests to Notion in order to obfuscate secrets. Obviously no local API will be active during the build, which I am guessing is the error I’m running into?

To illustrate – here’s the code for the pages that are to be generated:

import Head from 'next/head';

export default function Post( { postData, postBlocks } ) {
  console.log( { postData, postBlocks } );
  return (
    <>

      <Head>
        <title>Placeholder</title>
        <meta name="description" content="" />
      </Head>

      <h1>Placeholder</h1>

    </>
  )
}

// Get further info on the specific "Post" from Notion via my API
export async function getStaticProps( { params } ) {
  const postDataRequest = fetch( `${ process.env.API_ROOT }/posts/${ params.id }` );
  const postBlocksRequest = fetch( `${ process.env.API_ROOT }/blocks/${ params.id }` );

  const [ postData, postBlocks ] = await Promise.all(
    ( await Promise.all( [ postDataRequest, postBlocksRequest ] ) )
      .map( response => response.json() )
  );

  return {
    props: { postData, postBlocks: postBlocks.results },
    revalidate: 86400,
  };

}

// Fetch  all "Posts" from Notion via my API, get their ID and generate a static route for each 
export async function getStaticPaths() {
  const req = await fetch( `${ process.env.API_ROOT }/posts?limit=999` );
  const data = await req.json();

  const paths = data.results.map( page => {
    return { params: { id: page.id } };
  } )

  return {
    paths,
    fallback: false,
  };
}

I’ve also tried to start the API locally and build the project in another terminal, this didn’t work either. Have I missed something somewhere?

I have also published my project on GitHub for further inspection.