i cant use regex with matches

import { IsString, Matches, MaxLength, MinLength } from 'class-validator';

export class AuthCredentialsDto {
  @IsString()
  @MinLength(4)
  @MaxLength(20)
  username: string;

  @IsString()
  @MinLength(8)
  @MaxLength(20)
  @Matches(/((?=.*d)|(?=.*W+))(?![.n])(?=.*[A-Z])(?=.*[a-z]).+$/)
  password: string;
}

i try delete dist but not work for me anyone pls help me

Commenting out code with PHP & JS causing bug

This code seems to comment out the alert line out, any idea why?
If I remove “//test” then it seems to work though.
Not sure if it’s a PHP or JS Bug or it’s meant to uncomment the line below also?

<script>
//test <? //test ?>
alert("test");
</script>

In the page source shows as:

<script>
//test alert("test");
</script>

How do I create a link with JavaScript?

In this function I create a DIV with various values.

showIn(calendar) {
        if (
            this.date < dateString(calendar.weekStart) ||
            this.date > dateString(calendar.weekEnd)
        ) {
            $(`#${this.id}`).remove();
            return;
        }
        let eventSlot;
        if ($(`#${this.id}`).length) {
            eventSlot = $(`#${this.id}`);
        } else {
            eventSlot = $("<div></div>")
                .addClass("event")
                .attr("id", this.id)
                .click(() => this.clickIn(calendar));
        }

        let textoutput = this.sus + "-" + this.description;
        eventSlot
            .text(textoutput)
            .css("backgroundColor", `var(--color-${this.color})`)
            .css("white-space", "nowrap")
            .css("position", "relative")
            .appendTo(`.day[data-dayIndex=${this.dayIndex}] .slot[data-hour=${this.startHour}]`);
    }

Now I want to display the text as a link instead of the text that I define in these lines.

let textoutput = this.sus + "-" + this.description;
        eventSlot
            .text(textoutput)

I tried with .href() , setAttribute etc. Unfortunately I can’t get my desired result.

Unable to authenticate users using procore

I want to integrate OAuth authentication for procore in my app.But Im getting this error :
Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.

I have included client id,code as well as redirect-uri parameter in my url:

https://login.procore.com/oauth/authorize?client_id=<my-id>&response_type=code&redirect_uri=<my_url>

employee attendance magement is not working [closed]

https://www.sourcecodester.com/php/14433/employee-attendance-record-system-using-php.html this is the code i copy and there is a error
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘`’ at line 1 in C:xampphtdocsEARSadminemployee.php:44 Stack trace: #0 C:xampphtdocsEARSadminemployee.php(44): mysqli->query(‘SELECT * FROM e…’) #1 {main} thrown in C:xampphtdocsEARSadminemployee.php on line 44

please help me, im dying

Where to use Date.now function for saving data to database

I have a REST API server with Express, connects to MongoDB. Basically my app accept an input form to save some reports daily and of course the timestamp has to be that current time.

My question is, should I use Date.now() when creating the Request body (in the client-side) or should I use it on my server controller (server-side)?

In the second option, I could use the { default : Date.now() } on the model schema or inside model constructor in controller file.

Regardless what option I go with, the difference of the timestamp depends on how long it took to process the request. The body consists bit of data, mostly strings and number and does not exceed 100kb.

I’m curious how is people approach to this kind of problem

I have a question about the finished promise from the View Transitions Api. I don’t understand it so good

I have a question regarding the view transitions API. I understand that the finished promise is executed as soon as the ready promise is completed. But can anyone help me better understand why you would use this finished promise?

let lastClick;
addEventListener("click", (event) => (lastClick = event));

function navigateToCards(data) {
  if (!document.startViewTransition) {
    updateDOM(data);
    return;
  }

  const transition = document.startViewTransition(() => {
    updateDOM(data); 
  });

  
  transition.ready.then(() => {
    document.documentElement.animate(
      {
        transform: [
          `translateX(100%)`,
          `translateX(0%)`,
        ],
      },
      {
        duration: 300, 
        easing: 'ease-in-out', 
        pseudoElement: "::view-transition-new(cards)",
      }
    );
  });
} This will animate the cards on the other page when i navigate to this page. But can someone help me understand where for i can use the finished promise?

Lags when changing state (requestAnimationFrame)

I have the following audio player logic:
There is an audio track that plays sound and displays the current position of the audio using a line.
My problem is this:

  1. When the state changes, I often cause a redraw, which leads to lags in the application.
  2. Using requestAnimationFrame I cannot achieve smooth movement.

How can we use debounce or other methods so as not to overflow the stack when calling togglePlayer function and add smoothness to movement using requestAnimationFrame.
Audio is in buffer.

const [currentTime, setCurrentTime] = useState(0); 
const soundController = useRef<undefined | SoundDriver>(undefined); 
const soundInstance = new SoundDriver(audioFile);




<div
        id="waveContainer"
        ref={waveContainerRef}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
/>

Called when the button is clicked onClick(“play | pause | stop”). Also called when the current time state changes.
Time is displayed in seconds.
The updateCurrentTimeLine function takes the current time and displays a slider on the audio waveform.

const togglePlayer = useCallback(
    (type: string) => () => {
      if (type === "play") {
        soundController.current?.play();
        const updateCurrentTime = () => {
        // get the current time from the buffer
          const currentTime = soundController.current?.getCurrentTime() || 0;

          soundController.current?.updateCurrentTimeLine(currentTime);
          setCurrentTime(currentTime);
          requestAnimationFrame(updateCurrentTime);
        };
        updateCurrentTime();
      } else if (type === "stop") {
        soundController.current?.pause(true);
      } else {
        soundController.current?.pause();
      }
    },
    [currentTime]
  );

The slider started moving.

const handleMouseDown = useCallback(() => {
  setIsDragging(true); 
}, []);

Move the slider, changing its state and changing the current position.

const handleMouseMove = useCallback(
    (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
      if (isDragging && soundController.current && waveContainerRef.current) {
        soundController.current?.pause();
        const containerRect = waveContainerRef.current.getBoundingClientRect();
        const mouseX = event.clientX - containerRect.left;
        const duration = soundController.current.getDuration();
        if (duration !== undefined) {
          const newTime = (mouseX / containerRect.width) * duration || 0;
          setCurrentTime(newTime);

          // we transfer the current value for subsequent playback 
          soundController.current?.rewindTrack(newTime);
        }
      }
    },
    [isDragging]
  );

Rewind ends, playback starts.

const handleMouseUp = useCallback(() => {
  setIsDragging(false);
soundController.current?.play(currentTime);

}, [handleMouseMove]);

id is undefined in query endpoint [duplicate]

I have been using Redux-Toolkit Query (RTK Query) for a while now and this is the first time I see this. I am trying to edit a product however I cannot seem to be able to hit the correct url:

RTK Query:

editProduct: builder.mutation({
  query: (data) => ({
    url: `/api/products/${data.id}`,
    method: "PUT",
    body: data,
  }),
  invalidatesTags: ["Products"],
}),

For some reason I keep hitting "http://localhost:5173/api/products/undefined" even though I can see the id is correct, like so:

const formDataToSend = new FormData();
formDataToSend.append("id", formData.id);
formDataToSend.append("name", formData.name);
formDataToSend.append("description", formData.description);
formDataToSend.append("price", formData.price);
formDataToSend.append("category", formData.category);
formDataToSend.append("image", formData.image);
formDataToSend.append("productImage", formData.productImage);

console.log("formDataToSend:");

for (const [key, value] of formDataToSend.entries()) {
  console.log(`${key}:`, value);
}

try {
  await editProduct(formDataToSend).unwrap();
  toast.success("Product edited successfully");
  navigate("/admin/products");
} catch (error) {
  console.log(error);
  toast.error(error.data.message);
}

I do get all the values console.logged, i.e.:

formDataToSend:
AdminEditProduct.jsx:131 id: 663a714dd1b42a513610044d
AdminEditProduct.jsx:131 name: White shirt
AdminEditProduct.jsx:131 description: Elevate your wardrobe with our classic white shirts, a timeless essential for every modern wardrobe. Crafted from premium materials, our white shirts offer crisp elegance and versatility for any occasion. From boardroom meetings to casual outings, these shirts exude effortless sophistication and style. Discover the perfect balance of comfort and refinement with our collection of white shirts, designed to elevate your look with every wear.
AdminEditProduct.jsx:131 price: 6.99
AdminEditProduct.jsx:131 category: shirts
AdminEditProduct.jsx:131 image: null
AdminEditProduct.jsx:131 productImage: noimage.png

But always id is undefined, even though you can clearly see the id in the log, so I get this error from server:

PUT http://localhost:5173/api/products/undefined 500 (Internal Server Error)

This code is very similar to the one I am using when adding a product which works fine, but for some reason now when editing the data sent isn’t being recognized.

How can I add a header to a network request in Playwright

When I use the page.goto method, I need to add a header to one of the network requests that are made. I have worked out how to deleted a header (below), but cannot work out how to add:

await page.route(url, (route, request) => {
    const originalHeaders = request.headers();

    delete originalHeaders['authorization'];

    route.continue({
        headers: originalHeaders,
    });
})

Using the relative luminance, and ‘hue’ and ‘saturation’ values of a color, is it possible to derive its ‘lightness’ value in HSL color space?

I have an application where users select a color, and then the rest of the color scale is generated based on the selected color, for a total of 10 colors. Suppose I select golden yellow as my original color. The rest of the 9 colors, will be derived based on that color.

I want to maintain luminance even if the hue is changed. For example, in this image, all colors in at the same position have around the same luminance:

Color scale examples

I had been doing this derivation of colors in the RGB color space without any attention to perceived lightness/darkness of the derived colors.

Here’s how I had gone about it:

  1. First I derive the luminance of the selected color.
  2. Then, based on the luminance, I assign the color a position out of 10 on the color scale. I created a reference table of relative luminance value range for each color.
    Reference table of luminance value for each position in the color scale
  3. Now, the lighter and the darker colors need to be derived.

My idea is that if I convert the original color to HSL, then I can just modify the lightness value to achieve the rest of the colors. Basically, given a specific hue and saturation values, and knowing the desired luminance, I would like to derive the lightness values.

I also looked into the HCL color space but I don’t understand it, plus it seems complex. In HSL, I just need to change the lightness value, but in HCL, I think multiple values need to be changed.

I am not a programmer. I am a designer. I have little knowledge of Javascript. I tried these things out to the best of my knowledge and using ChatGPT, but I have reached my limit.

Please help me. I don’t even know if what I am trying to do is possible or not. Maybe it’s not the best way to do it. If you can suggest an alternative approach, that too would be great too.

How to zoom on an image when the user scrolls to a specific section on the page?

I’m zooming on an image when user scrolls on the page. In my case, I zoom to letter L on the image. It all works fine however, I want to zoom the image to letter L when the user scrolls to a particular section on the site, rather than what it does currently which is zooming as soon as the image loads. In my example I want the image to zoom in to letter L when user scrolls to this text – “Aliquam aliquam a est eget cursus” and zoom out when it reaches to the end of the next paragraph (eugiat ipsum.). How can I achieve this? Here is my code –

const d1 = document.querySelector('.d1')
const d1InitialY = d1.offsetTop
document.addEventListener("scroll", evt => {
  const r = scrollY - d1InitialY
  const s = r < 0 ? 1 : 1 + (r / 200)
  d1.style.backgroundSize = (s * 100) + '%'
})
.d1 {
  width: 100%;
  aspect-ratio: 2/1;
  position: sticky;
  top: 0;
  background-image: url(http://picsum.photos/id/451/1500/750);
  background-size: 100%;
  background-position: 72% 43%;
}
<div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempor nunc mauris, sit amet placerat tortor lobortis dapibus. Nam lectus eros, maximus ac magna vel, congue consequat eros. Fusce id pretium diam. Cras sit amet pharetra ante. Sed quis commodo quam, vel facilisis ipsum. Vestibulum sodales iaculis arcu, et fringilla nisi ullamcorper sed. Donec interdum sit amet est non accumsan. Donec non augue feugiat, fermentum nunc non, convallis est. Cras vel ligula nec odio faucibus ultricies. Sed vulputate tortor eget pretium convallis. Cras interdum elit eget mi porta suscipit. Morbi ut velit diam. Etiam finibus eros et efficitur rutrum. Quisque viverra metus ac eleifend imperdiet. Quisque pretium ut purus vitae tempus. Duis varius risus congue velit faucibus, sed interdum purus consectetur.
</p>
<div class="d1"></div>
<p>
Cras volutpat velit non mi sagittis condimentum. Cras tempor aliquet turpis sed pretium. Nunc aliquet sodales turpis quis ultrices. Duis auctor accumsan enim, quis maximus ex malesuada a. Donec a felis ut erat tempus euismod non vel neque. Proin lectus massa, sagittis at imperdiet nec, consequat ut neque. Sed vel placerat neque, vel varius urna. Vivamus interdum euismod urna a accumsan. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
<p>
Nulla rhoncus aliquam mauris, eu pretium dolor auctor in. Maecenas a sollicitudin dolor, eget commodo quam. Proin et dui sed ligula vulputate egestas. Quisque eget augue vitae purus placerat pharetra. Aliquam rhoncus convallis lorem, sed facilisis odio blandit scelerisque. Vivamus viverra urna ac nulla interdum, eget ullamcorper leo maximus. Mauris nec feugiat enim. Nam congue, dui sit amet vestibulum posuere, leo mauris fermentum lorem, eget bibendum velit nunc quis leo.
</p>
<p>
Curabitur eget ullamcorper justo, sit amet dictum neque. Fusce vitae ligula et felis auctor vulputate vel suscipit nibh. Integer a felis varius purus vestibulum viverra. Morbi venenatis placerat augue sit amet commodo. Sed dapibus molestie eros, vitae ultrices nunc commodo aliquam. Vivamus tempus mollis massa vel egestas. Donec ut ante quis eros commodo volutpat. Proin sem nisi, viverra ac sem tristique, consectetur laoreet sapien. Vivamus suscipit orci vel euismod scelerisque. Nullam sed pulvinar tellus. Nullam pulvinar arcu eget nibh rutrum, eget faucibus ligula ullamcorper.
</p>
<p>
Sed sed cursus leo. Nam molestie eleifend leo, nec fermentum risus maximus ac. Pellentesque eget placerat ipsum. Vestibulum tempor quam justo. Fusce dapibus turpis non ante faucibus suscipit. Fusce rhoncus eleifend ipsum et lacinia. Curabitur nec congue arcu. Mauris dignissim magna ligula. Nullam ultrices, metus sit amet ultrices porttitor, turpis ligula interdum enim, eu pellentesque purus quam ut arcu. Nullam aliquet vitae tortor vel tincidunt. Fusce maximus lacus diam, sed elementum ligula condimentum vel. Sed consequat orci ac nunc gravida, at accumsan magna porttitor.
</p>
<p>
Mauris vulputate quam ac purus laoreet, nec ultrices eros placerat. Fusce id nisi ex. Nunc ornare tellus nisl, suscipit fermentum quam sodales sit amet. Ut ex magna, tempor nec ex sed, ornare ornare sem. Proin gravida turpis urna, vitae posuere purus consequat sit amet. Donec laoreet tempor massa. Praesent porta mauris vitae neque condimentum, non volutpat felis eleifend.
</p>
<p>
Aliquam aliquam a est eget cursus. Ut eu tempus justo, rutrum dapibus ex. In hac habitasse platea dictumst. Nulla ornare nisi sit amet arcu semper maximus. Praesent eu augue eget mi sodales sodales. Praesent sodales neque malesuada, euismod est in, lobortis turpis. Nam blandit facilisis mauris. Ut ac ex rhoncus, ornare velit ac, aliquam nibh. Quisque euismod mauris quis nisl consectetur vulputate. Pellentesque mattis, tellus ut dictum dictum, urna ligula sodales magna, euismod malesuada ipsum quam nec elit.
</p>
<p>
Duis sit amet eros non est lacinia posuere et et ex. Proin in dui ornare ex eleifend pharetra. Etiam eros urna, euismod eget porttitor et, tempor quis turpis. Nullam sollicitudin suscipit lorem, maximus pellentesque turpis dictum sed. Integer fringilla gravida tellus sit amet facilisis. Pellentesque vel porta justo. Proin vehicula eget tortor ut condimentum. Phasellus interdum urna a condimentum dapibus. Sed commodo elit a metus vestibulum, ac vehicula mi tincidunt. Duis ante quam, posuere eget purus et, mollis congue tortor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc quis orci porttitor, dictum libero sit amet, feugiat ipsum.
</p>
<p>
Nunc auctor lorem vitae neque sodales cursus. Sed scelerisque tempor tincidunt. Praesent eu pretium mi. Duis vitae venenatis nunc. Integer dolor sapien, vehicula ac dui id, fermentum malesuada justo. Donec ullamcorper enim sed nulla egestas condimentum. Etiam vitae dapibus sem, ut efficitur nulla. Donec laoreet, nunc quis aliquet blandit, erat nibh facilisis nibh, ut fermentum nisl dolor vel dui. Nunc pulvinar scelerisque urna, ut dictum purus placerat ac.
</p>
<p>
Nam mattis ipsum at metus placerat maximus. Sed sed enim nunc. Aenean dapibus, lorem non congue volutpat, tortor orci egestas leo, eu efficitur erat orci sit amet libero. Praesent quis convallis metus. Cras eget ligula nec tortor mollis vestibulum et facilisis tellus. Aliquam erat volutpat. Sed malesuada, lectus vulputate tristique mattis, lacus nisl tempus sem, in aliquet dolor neque sed nisl. Nulla facilisi. Nulla a pharetra felis, eu aliquet urna. Phasellus mattis mauris eget mauris laoreet, et accumsan magna laoreet. Maecenas a condimentum diam. Integer et neque odio.
</p>
<p>
Etiam feugiat tempus nibh, quis mattis enim porttitor eu. Praesent congue gravida nisi, sit amet convallis lectus sagittis et. Praesent rutrum ante nec lectus congue, congue pharetra sem efficitur. Vivamus eros mauris, pellentesque in aliquam at, vehicula consequat neque. Sed in pharetra lorem. Vivamus porttitor lectus risus. Vestibulum malesuada vestibulum ullamcorper. Nulla lacus purus, faucibus sit amet urna ac, placerat congue lectus. Ut iaculis risus eu pretium cursus. Quisque ac pharetra orci, ut convallis libero. Praesent auctor commodo quam sit amet aliquam. Integer tortor neque, cursus sit amet maximus sit amet, ultrices sed arcu. Nulla volutpat libero non ipsum auctor consectetur. Cras non malesuada felis, vel maximus ligula. Curabitur euismod porta semper. Ut posuere eget libero ac consequat.
</p>
<p>
Mauris tristique, leo sit amet aliquam varius, urna elit scelerisque nisi, non iaculis lectus augue id sapien. Phasellus euismod tellus in sodales finibus. Suspendisse potenti. Aenean malesuada sapien quis eleifend volutpat. Cras quam arcu, iaculis vel ornare vulputate, feugiat quis enim. Nullam auctor, libero vestibulum imperdiet tincidunt, justo tellus varius justo, a finibus magna purus eu est. Nam interdum odio in ligula ultricies, quis pulvinar lectus pulvinar. Fusce quis sem tincidunt, mattis massa eu, bibendum enim. Vivamus arcu arcu, aliquam eget suscipit id, tempor sed nibh. Nullam mi mauris, facilisis vitae massa a, facilisis vulputate velit. Phasellus facilisis egestas erat id elementum.
</p>
</div>
<p>
Proin non libero tortor. Nam scelerisque vel odio interdum pretium. Sed non metus magna. Praesent ullamcorper venenatis risus, quis semper purus. Donec vitae lectus id magna dignissim laoreet at ac urna. Aenean sapien dolor, egestas vitae nisl quis, ornare ullamcorper nibh. Nulla facilisi. Fusce maximus dapibus scelerisque. Donec sagittis leo mi, eget aliquet odio sodales rhoncus.
</p>
<p>
Nunc sollicitudin risus feugiat lacinia luctus. Vivamus iaculis ultrices blandit. Sed lobortis varius dapibus. Fusce vel justo eu est elementum ultricies eget vel dolor. Donec faucibus ex eget leo interdum, maximus accumsan orci pellentesque. Suspendisse interdum dolor lectus, et venenatis massa posuere eu. Etiam cursus lorem vitae tortor consectetur vestibulum.
</p>
<p>
Maecenas id lectus at velit euismod venenatis a ac dolor. Nullam quis volutpat ante, eu congue quam. Aliquam a gravida massa. Ut hendrerit in odio sed fermentum. Aliquam erat volutpat. Donec sed odio interdum, aliquam augue a, vulputate lorem. Nulla sed mattis odio. Sed volutpat tincidunt mauris sit amet porta. Etiam non nisi odio.
</p>

Generate an array of numbers between a range such that every number has 2 or 4 occurences

I have an array of items between 1 to 8. I want to select an item from that array and have it in a new array such that the item occurs either 0, 2 or 4 times in the new array.

const firstArr = [4, 2, 1, 7, 8, 3, 5, 6]; //array of items between 1 to 8
const secondArr = [1, 1, 7, 6, 7, 7, 8, 7, 1, 3, 1, 6] //should contain a number
// in firstArr and that number must occur 0, 2, 4 times.

The max length of secondArr must be 12.

I tried something like:

while(secondArr.length <= 12){
   //select random index from firstArr and fill secondArr until the number at index is even
}

But this almost goes into an infinite loop.

No valid addresses for Libp2p node

I´m trying to create a node with lib but when I add the addresses filed, the next error comes out:

P2PService.js:83 Error al crear el nodo: CodeError: no valid addresses were provided for transports [@libp2p/websockets]
    at DefaultTransportManager.listen (transport-manager.ts:260:1)
    at DefaultTransportManager.afterStart (transport-manager.ts:75:1)
    at components.ts:75:1
    at Array.map (<anonymous>)
    at Proxy._invokeStartableMethod (components.ts:71:1)
    at Proxy.afterStart (components.ts:90:1)
    at Libp2pNode.start (libp2p.ts:217:1)
    at async createLibp2p (index.ts:170:1)
    at async createNode (P2PService.js:60:1)

I made sure the port was available and even tried different ones but it’s impossible to get my node to work. I’m trying to create a chat app that connects individual nodes to a hub and then provide their emails to find each other. Please I need help, this is very urgent.
The code is this:

import { createLibp2p } from 'libp2p'
import { createFromJSON } from '@libp2p/peer-id-factory'
import { webSockets } from '@libp2p/websockets'
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { kadDHT } from '@libp2p/kad-dht'
import PeerId from 'peer-id'
import { generateKeyPairFromSeed } from '@libp2p/crypto/keys'

const chatProtocol = '/mychat/1.0.0'

export async function createPeerId(privKey) {
  try {
    
    const peerIdPrivateKey = await generateKeyPairFromSeed("Ed25519", privKey)
    console.log('peerIdPrivateKey:', peerIdPrivateKey)

    const peerId = await PeerId.createFromPrivKey(peerIdPrivateKey.bytes)
    console.log('peerId:', peerId)

    localStorage.setItem('peerId', JSON.stringify(peerId))
    console.log('Archivo JSON escrito con éxito')

  } catch (error) {
    console.error('Error al crear el PeerId:', error)
  }
}

function getStoredPeerId() {
  const peerDataJSON = localStorage.getItem('peerId')
  if (!peerDataJSON) {
    console.error('No se encontraron datos de PeerId en localStorage')
    return null
  }
  return JSON.parse(peerDataJSON)
}

export async function createNode(privKey) {

  await createPeerId(privKey)

  const storedPeerId = getStoredPeerId()
  console.log('PeerId almacenado recuperado:', storedPeerId)

  const peerId = await createFromJSON(storedPeerId)
  console.log('PeerId creado desde el JSON:', peerId)

  if (!peerId) {
    console.log('No se encontraron datos de PeerId')
    return
  }

  try {
    const node = await createLibp2p({
      peerId: peerId,
      addresses: {
        listen: ['/ip4/127.0.0.1/tcp/10333']
      },
      transports: [webSockets()],
      connectionEncryption: [noise()],
      streamMuxers: [yamux()],
      services: {
        dht: kadDHT({
        })
      }      
    })
    
    await node.start()
    console.log('libp2p has started', node)

    const listenAddrs = node.getMultiaddrs()
    console.log('libp2p is listening on the following addresses: ', listenAddrs)

    return node
    
  } catch (error) {
    console.error('Error al crear el nodo:', error)
  }
}

How to trigger a function for each document insertion with Mongoose?

I want to trigger a function each time an element is inserted/created in a collection, not when it’s updated. (And I need the ID of the element created)

Here’s what I did:

schema.pre("save", function() {
    this.$locals.wasNew = this.isNew;
});

schema.post("save", function() {
    if (this.$locals.wasNew) {
        console.log(`User ${this.id} created!`);
    }
});

It works with calls like this one:

await UserModel.create({
    mail
});

But not with calls like this one:

const user = await UserModel.findOneAndUpdate(
    { mail },
    { $set: { mail } },
    { new: true, upsert: true }
);

It seems like upsert does not trigger the save hook with the isNew boolean set to true.

Am I doing it wrong? Missing something? Or is there an alternative way of doing it?