I am trying to fetch top rated 3 products


// @route   GET /api/products/top
// @desc    Get top rated products
// @access  Public
router.get(
  '/top',
  asyncHandler(async (req, res) => {
    const products = await Product.find({}).sort({ rating: -1 }).limit(3)

    res.json(products)
  })
)

enter image description here

Cast to ObjectId failed for value “top” (type string) at path “_id” for model “Product”

[enter image description here][1]

lowdb and other dependencies not functioning or being added to package.json

I have been trying to install lowdb due to this error I keep getting with my code in the terminal:

nodemon] starting `node index.js`
/Users/brit/Documents/MIT/week24/controller/users-controller.js:2
const low = require("lowDB");
            ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/brit/node_modules/lowDB/lib/index.js from /Users/brit/Documents/MIT/week24/controller/users-controller.js not supported.
Instead change the require of index.js in /Users/brit/Documents/MIT/week24/controller/users-controller.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/brit/Documents/MIT/week24/controller/users-controller.js:2:13)
    at Object.<anonymous> (/Users/brit/Documents/MIT/week24/routes/users-route.js:12:5)
    at Object.<anonymous> (/Users/brit/Documents/MIT/week24/index.js:4:20) {
  code: 'ERR_REQUIRE_ESM'
}

Node.js v19.0.0

so I tried to install lowdb again and got these errors, although it seems like it was still installed…:

MIT npm install lowdb
npm WARN brit No description
npm WARN brit No repository field.
npm WARN brit No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-freebsd-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"freebsd","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-android-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"android","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-darwin-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"darwin","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-arm-gnueabihf):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"arm"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-arm64-gnu):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-x64-gnu):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-win32-x64-msvc):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"win32","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-arm64-musl):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-win32-arm64-msvc):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"win32","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-x64-musl):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-win32-ia32-msvc):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"win32","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-android-arm-eabi):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"android","arch":"arm"} (current: {"os":"darwin","arch":"x64"})

+ [email protected]
updated 1 package and audited 823 packages in 7.797s

61 packages are looking for funding
  run `npm fund` for details

found 8 vulnerabilities (4 moderate, 2 high, 2 critical)
  run `npm audit fix` to fix them, or `npm audit` for details

I tried npm audit fix. I tried deleting node and npm and reinstalling I am not sure what the issue is but this is all my package.json says still:

{
  "name": "week21",
  "version": "1.0.0",
  "description": "MIT xCode assignment",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "nodemon index.js --ignore db.json"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

Javascript: Return specific keys from JSON as Array

So I am practicing javascript and I can’t seem to make this work. I am trying to console log a JSON API as an array, but only the title key:value pair is what I need to display.
This is the expected output I am trying to achieve.
enter image description here

However, this is the output that I’m getting:
enter image description here

Not so sure where I’m wrong, here is my code:

fetch("https://jsonplaceholder.typicode.com/todos")
.then((res) => res.json())
.then((res) => console.log(Array = [res.map((data) => data.title)]));

Django Channels: Real time application, update other rooms when any action appears

For now I’ve created a consumer that can handle one-to-one connections as a private chat. In my UI I display previous conversations and I’d love to somehow update their content if new message or conversation appears and then apply some actions, so for example slide the previous conversation to the top if it contains a new message.

So it’s like in any bigger application as instagram or facebook. When you’re chatting with someone and if any new message appears from other sender, not the one that you’re chatting with, the previous conversations are being updated, so in this case slide the previous or new conversation to the top of conversations.

I’m not really familiar with websockets and I want to find the way how can I do that. As I understand if consumer let’s two users connect to one room (layer?) how can other messages be updated? websocket does not know anything about it?

I’ve tried brainstorming, but I still didn’t get it right.

This is my consumer as i’ve mentioned before, it only can only support two connections between two users.

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.user = self.scope["user"]
        self.private_chat_room_id = self.scope['url_route']['kwargs']['private_chat_room_id']
        self.room_group_name = f'private_{self.private_chat_room_id}'

        if self.user.is_anonymous:
            await self.close()
        else:
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )

            await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        data = json.loads(text_data)
        message_content = data["message"].strip()

        if message_content:
            # Create chat message object
            message_dict = await self.save_message(self.private_chat_room_id, self.user.id, message_content)
            message_dict["is_author"] = message_dict["author_id"] == self.user.pk,

            await self.channel_layer.group_send(
                self.room_group_name,
                {"type": "chat_message", "message_dict": message_dict}
            )

    async def chat_message(self, event):
        message_dict = event["message_dict"]
        message_html = render_to_string("chat/message_ajax.html", {"conversation_messages": [message_dict]})

        await self.send(text_data=json.dumps({"type": "chat", "html": message_html, "message_id": message_dict["pk"]}))

    @database_sync_to_async
    def save_message(self, room_id, author_id, message):
        return PrivateRoomChatMessage.objects.create(
            content=message,
            room_id=room_id,
            author_id=author_id,
        ).to_dict()

This is my front-end logic to handle only new messages between two users:

           const chat_socket = new WebSocket(`ws://${window.location.host}/ws/chat/{{ conversation_id }}/`);

            const spinner = $(".spinner-backdrop");

            chat_socket.onmessage = (e) => {
                let data = JSON.parse(e.data);

                if(data.type === 'chat'){
                    // Reset message form
                    message_input.val("");

                    is_form_valid = null;
                    message_form.removeClass("invalid");
                    form_submit_btn.removeClass("valid");
                    form_submit_btn.attr("disabled", false);

                    // Render new messages
                    messages.prepend(data.html);

                    // Scroll to the first image
                    $(`li#${data.message_id}`)[0].scrollIntoView();
                }
            }`

                                                                                                   '

Angular – MatSort doesn’t work when I use custom MatTable with HttpDatabase

I have a custom table component(MatTable) and my columns are passed by ng-content, but when I try change MatSort, my table doesn’t update…

My table component HTML :

      <div class="table-container">
    <table
      mat-table
      matSort
      [dataSource]="data"
      matSortActive="created"
      matSortDisableClear
      matSortDirection="desc"
    >
      <ng-content select="[columns]"></ng-content>

      <tr
        mat-header-row
        *matHeaderRowDef="displayedColumns"
      ></tr>

      <tr
        mat-row
        *matRowDef="let row; columns: displayedColumns"
      ></tr>

      <tr
        class="mat-row"
        *matNoDataRow
      >
        <td
          *ngIf="!loadingData"
          class="mat-cell no-data"
          [attr.colspan]="data"
        >
          <p class="no-data-text">{{ noDataMessage }}</p>
        </td>
      </tr>
    </table>
  </div>

  <mat-paginator
    [pageSize]="20"
    showFirstLastButtons
    [length]="totalResults"
  ></mat-paginator>
</div>

Table component TypeScript file :

import {
  Component,
  ViewChild,
  AfterViewInit,
  AfterContentInit,
  Input,
  Output,
  EventEmitter,
  ContentChildren,
  QueryList,
} from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatColumnDef, MatTable } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { BreakpointObserverService } from '@ndd-averba/shared/services';
import { ITablePaginator } from '@ndd-averba/shared/interfaces';

@Component({
  selector: 'ndd-averba-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.scss'],
})
export class TableComponent<T> implements AfterViewInit, AfterContentInit {
  @Input() public displayedColumns!: string[];
  @Input() public data!: Array<T>;
  @Input() public loadingData!: boolean;
  @Input() public noDataMessage!: string;
  @Input() public totalResults!: number;
  @Output() public loadDataEvent!: EventEmitter<ITablePaginator>;

  @ContentChildren(MatColumnDef) columnDefs!: QueryList<MatColumnDef>;

  @ViewChild(MatTable, { static: true }) table!: MatTable<T>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort!: MatSort;

  constructor(protected breakpointObserverService: BreakpointObserverService) {
    this.loadDataEvent = new EventEmitter();
  }

  ngAfterContentInit(): void {
    this.columnDefs.forEach((columnDef) => {
      this.table.addColumnDef(columnDef);
    });
  }

  ngAfterViewInit(): void {
    this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0));
    this.loadDataEvent.emit({
      sort: this.sort,
      paginator: this.paginator,
    });
  }
}

I have another component that use this table and pass columns by ng-content. It receive EventEmitter from table component to render data from API. Can anybody help me?

Convert a string with commas to a multidimensional object javascript

I have a big JSON file with “key:value” format like this:

{
    "str1,str2,str3,str4,title": "VALUE OS THIS KEY",
    "str1,str2,str3,str4,description": "VALUE OS THIS KEY",
    "str1,str2,str3,str4,value": "VALUE OS THIS KEY",
    ...
    "str1,str2,str3,str5,title": "VALUE OS THIS KEY",
    "str1,str2,str3,str5,description": "VALUE OS THIS KEY",
    ...
    "str1,str_other,str3,str4,title": "VALUE OS THIS KEY",
    ...
}

And I want to transform this keys into an object to make a new JSON and work with it like this:

{
  str1:{
    str2:{
      str3:{
        str4:{
          title: "VALUE OS THIS KEY",
          description: "VALUE OS THIS KEY",
          value: "VALUE OS THIS KEY"
        },
        str5:{
          title: "VALUE OS THIS KEY",
          description: "VALUE OS THIS KEY"
        }
      }
    },
    str_other: {
      str3:{
        str4:{
          title: "VALUE OS THIS KEY"
        }
      }
    }
  }
}

I try it with javascript forEach but I don’t know how to create this multidimensional array.
Can anyone show me how to do that?

Thank you very much in advance

Sending an api request with python works, but the exact same request sent from wix velo (javscript) returns a 400 error

I’m working with a REST API that requires authentication. I sent a request from my local machine using python and Got a successful response. When I did the same request using javascript (hosted on Wix Velo) I got a 400 error. I’ve used a request grabber to compare the bodies of the two requests. They’re identical. Below is the information that the request grabber gave me about the requests.

Successful python request info (Body hidden as it’s identical to the one in the other request)

Accept: /
Accept-Encoding: gzip, deflate, br
Authorization: Bearer <my_API_key>
Connection: keep-alive
Content-Length: 376
Content-Type: application/json
User-Agent: python-requests/2.28.1s.

Unsuccessful JS request info

Connection: close
Accept: /
Accept-Encoding: gzip,deflate
Authorization: Bearer <my_API_key>
Connection: close
Content-Length: 376
User-Agent: node-fetch/1.0 (+https://github.com/bitinn/node-fetch)

Any insight into why exactly the request is not working from the web would be wonderful.

I’ve really tried everything. I verified that the python request works, I verified the bodies are received as the exact same text. I know my API key works. I don’t think it could be a CORS error as I can use my wix-hosted JS to do other things with that API.

requests are not sent from the server

I don’t know how to explain it correctly.
In general, I can’t make a request to my server from the project using: axios, needle, fetch, it doesn’t even send the request, it just gives out `data: ”I don’t know how to fix it, sorry I don’t even know how to explain it to you
There is no request on the server side.

But if I start using third-party programs like insomnia and stuff like that.
It sends and works. Maybe someone has encountered this problem
standart request:

axios.post('http://localhost:3000/params..') // return data: ''

how to load script in one page form another page

I have two page index.html and chart.html. I want section or of chart.html to load in index.html. The tag contains script for graph. Chart.html contains many divs but i want only to load div that has id of loadgraph in index.html page

index.html

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<button onclick="window.print()">Download Annual Report</button>


<div id='graph'> </div>



<script>

$(document).ready( function() {

 $('#graph').load('chart.html #loadgraph');


 });
</script> 

</body>
</html>

and chart.html contains

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> 
</head>
<body>
<div id='loadgraph'>
  
<h1>This is Graph Chart</h1>

<canvas id="mixed-chart" width="800" height="350"></canvas>

<script type="text/javascript">
  
new Chart(document.getElementById("mixed-chart"), {
    type: 'bar',
    data: {
      labels: ["2077", "2078", "2079"],
      datasets: [{
          label: "Diploma in Forestry",
          type: "line",
          borderColor: "#e8c3b9",
          data: [37,36,18],
          fill: false
        },{
          label: "Diploma in Civil",
          type: "line",
          borderColor: "#c45850",
          data: [48,47,48],
          fill: false
        },  {
          label: "Diploma in Animal Science",
          type: "line",
          borderColor: "#3cba9f",
          data: [29,19,34],
          fill: false
        },{
          label: "Diploma in Pharmacy",
          type: "line",
          borderColor: "#8e5ea2",
          data: [0,0,40],
          fill: false
        },{
          label: "Diploma in Forestry",
          type: "bar",
          backgroundColor: "#e8c3b9",
          data: [37,36,18],
        },{
          label: "Diploma in Civil",
          type: "bar",
          backgroundColor: "#c45850",
          data: [48,47,48],
        },  {
          label: "Diploma in Animal Science",
          type: "bar",
          backgroundColor: "#3cba9f",
          data: [29,19,34],
        },{
          label: "Diploma in Pharmacy",
          type: "bar",
          backgroundColor: "#8e5ea2",
          data: [0,0,40],
        }
      ]
    },
    options: {
      title: {
        display: true,
        text: 'Total Diploma Seats: Forestry: 40  Civil: 48   Animal Science: 40   Pharmacy 40'
      },
      legend: { display: true }
    }
});
</script>

</div>
</body>
</html>

Any help would be greatly appreciated.

ServiceWorkers: what’s the difference between importScripts and self.importScripts

I manage multiple sites that use third party services for sending push notifications. The services require registering a service worker and they each supply the code for the service worker.

One has

importScripts('https://url-of-their-js-file');

and the other has

self.importScripts('https://url-of-their-js-file');

That’s it for each of them. There’s no scoping or functions or anything.

According to MDN:

The self read-only property of the WorkerGlobalScope interface returns a reference to the WorkerGlobalScope itself

So then why is self necessary at all? Are these two lines any different or can I just remove self. from the second one?

How to correctly read and write any file in Jacascript?

I am building a form that allows a user to upload any file. Unfortunately, the file comes out distorted for non-simple file types such as .pdf (it works for simple .txt).

To test out that I am reading files correctly, I am using the following helper, as per this:

const makefile = (content: string) => {
  // Create element with <a> tag
  const link = document.createElement("a");

  // Create a blog object with the file content which you want to add to the file
  const file = new Blob([content], { type: "application/pdf" });

  // Add file content in the object URL
  link.href = URL.createObjectURL(file);

  // Add file name
  link.download = "sample.pdf";

  // Add click event to <a> tag to save file.
  link.click();
  URL.revokeObjectURL(link.href);
};

The helper creates an output file from the fed-in content.

I am reading and writing the file with:

  const onFinish = async (values: FormProps) => {
    const file = values.file?.originFileObj; // File type
    const reader = new FileReader();
    reader.addEventListener("load", (event) => {
      const binaryString = event.target?.result as string;
      makefile(binaryString);
    });

    if (!file) {
      return;
    }

    reader.readAsBinaryString(file);
  };

If everything works correctly, the downloaded sample.pdf should be identical to the input file read from the reader. However, that is not the case for more involved file types, such as .pdf.

The resulting file is corrupted and pdf readers can’t read it. It also comes out greater in size than the input file (for instance, 326KB output file size vs 222KB input file size).

I have tried different ways of reading the file, to no avail – all produce invalid output. What could be the issue?

How can I pass an ID name into jQuery as a parameter?

I have the following code which toggles the visibility of an item with a certain ID:

<div onClick="toggleViz()">Click this</div>

<div id="item1" style="display: none;">
   <p>Item 1       
</div>

<div id="item2" style="display: none;">
   <p>Item 2       
</div>

<script>
function toggleViz() {
    var x = document.getElementById("item1");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</script>

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

I’d like to pass the ID name of the item whose visibility I want to toggle to the function as a parameter, so I don’t have to write a new function for every item.

When I try this:

<div onClick="toggleViz(item1)">Click this 1</div>
<div onClick="toggleViz(item2)">Click this 2</div>


<div id="item1" style="display: none;">
   <p>Item 1       
</div>

<div id="item2" style="display: none;">
   <p>Item 2       
</div>

<script>
function toggleViz(id_name) {
    var x = document.getElementById(id_name);
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</script>

I get: Uncaught TypeError: Cannot read properties of null (reading 'style')

Animation of waves from numbers three.js

I’m trying to make waves consisting of numbers. I have a ready-made example consisting of dots.

It works, but I don’t understand how you can replace dots with numbers.

I use three.js

this.geometry = new THREE.PlaneBufferGeometry(4, 4, 128, 128);
    const material = new THREE.ShaderMaterial({
      uniforms: uniforms,
      linewidth: 100,
      vertexShader: this.vertexShader(),
      fragmentShader: this.fragmentShader()
    });

// const material = new THREE.MeshStandardMaterial();
this.mesh = new THREE.Points(this.geometry, material);
scene.add(this.mesh);`

Git Hub Repository