Mongoose Schema show the array if a friendId exist in Users Model schema

I have created a user which has its login data and into it is has some arrays including friends, groups, pages and other stuff.
But I am stucked when I want see who has sent me a friend request.
So I have am trying to create the friend request/response as in Facebook.
My logic it is for the moment when I send you a friend request I add to my array of friends and then with post request I can see at which users is my ID added and it has the status Pending.
For the moment I have tried something but I am getting empty array as response.
My code is below.

user.service.js backend

const User = require("../models/user");
async function findYourPendingContact({friendId}) {
    return await User.find({friends: friendId});
}

module.exports = {
    findYourPendingContact
}

routes.js

routes.post("/user-friends", UserController.findYourContacts);

This is the Controller.

const userService = require("../service/user.service");
async findYourContacts(req, res, next) {
    let friendId = req.body.friendId;
    userService.findYourPendingContact({friendId: friendId})
    .then(friends => res.json(friends))
    .catch(err => next(err));
}

So seems my Database Json.
The user that added me as friend.

{
    "_id" : ObjectId("620bfd2d860fd314fc538df3"),
    "firstName" : "Max",
    "email" : "[email protected]",
    "lastName" : "Muster",
    "password" : "$2b$10$D8l15CTZHbp/rcApqXpwT.KUbHAg0hBYp0h1qounnKFW.plDO9wKe",
    "phone" : {
        "number" : "1234566",
        "countryCode" : "DE",
        "dialCode" : "+49",
        "e164Number" : "+491234566",
        "internationalNumber" : "+49 1234566",
        "nationalNumber" : "1234566"
    },
    "gender" : 1,
    "birthday_day" : "13",
    "birthday_month" : "8",
    "birthday_year" : "1998",
    "friends" : [
        {
            "friendId" : "6204605617d5fcc3c179f3cc", // this here is my ID
            "status" : 0,
            "createdDate" : {
                "$date" : 1644971031461
            }
        }
    ],
    "__v" : 0
}

Here are my Data on backend

{
    "_id" : ObjectId("6204605617d5fcc3c179f3cc"),
    "firstName" : "Test",
    "email" : "[email protected]",
    "lastName" : "Test",
    "password" : "$2b$10$koGb0fIcdWvq2ugGQXF7.OOmoof1QCH8IKQtoMGl9MHSJuu5Xumd6",
    "phone" : {
        "number" : "01234567",
        "countryCode" : "DE",
        "dialCode" : "+49",
        "e164Number" : "+4901234567",
        "internationalNumber" : "+49 01234567",
        "nationalNumber" : "01234567"
    },
    "gender" : 0,
    "birthday_day" : "8",
    "birthday_month" : "5",
    "birthday_year" : "1994",
    "__v" : 0
}

Now this is the part of my frontend when I login.

 public getUserFriends(userId): Observable<any> {
    const api = `${this.baseUrl}/user-friends`
    return this.http.post(api, JSON.stringify({friendId: userId}), this.httpOptions).pipe(
      map((response: User) => {
        console.log(response);
        return response;
      },
      (err) => {
        throw err;
      })
    )
  }

user.helper.ts

  showPendingFriends(authId): Observable<any> {
    return new Observable<any>(observer => {
      this.userService.getUserFriends({friendId: authId}).subscribe(response => {
        observer.next(response);
      })
    })
  }

components.ts

 this.userHelper.showPendingFriends(this.authService.userID).subscribe(res => console.log(res));

mapping keys of Object in javascript

I would like to change key names in such object:

const data = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4',
}

with those keys from map:

const map = {
'key1': 'change1',
'key4': 'change4'
}

Using code below:

const replacedKeysInData = Object.keys(data).map((key) => {
const keyFromMap = map[key] || key;
return { [keyFromMap]: data[key] }
})
console.log(replacedKeysInData);

I get:

[
{ change1: 'value1' },
{ key2: 'value2' },
{ key3: 'value3' },
{ change4: 'value4' }
]

The point is that I would like to have it in one object:

{ 
change1: 'value1',
key2: 'value2',
key3: 'value3',
change4: 'value4' 
}

I suppose it is simple, how can I do it?
Thanks

How to do API endpoint testing in Express JS using JEST?

There is an app with a several Express JS endpoints that are dependent on a MongoDB database ( Atlas to be more specific )

I’ve been struggling to figure out how to write appropriate integration tests with Jest testing framework.

First steps I want to accomplish:

  • To have an local testing database connection when the tests are run.
  • To start the application in test environment and wait for the database to successfully connect first before running the tests.

Current situation:

  1. App is being required from a module ( this executes the code and the app starts as like in normal development environment ).
  2. Tests takes place.
  3. Test results being outputted to the console.
  4. Information about whether database connection is succeeded or not follows up.

I assume that as per standard asynchronous behavior of NodeJS the tests are in some sort of racing condition with the database connection.

Would be awesome if someone could give me a hand understanding this environment switching from development to testing or any references to articles or any sort of information would be appreciated.

const request = require('supertest')
const app = require('../dist/app')

describe('Authentication API testing', () => {
    it('SHOULD RETURN Content-Type: application/json HEADER WITH Content-Length: 54 AND HTTP STATUS CODE 400 WHEN DOING POST /auth/register WITHOUT EMAIL ', () => {
        return request(app)
            .post('/auth/register')
            .send({ password: 'testPassword' })
            .expect('Content-Type', /json/)
            .expect('Content-Length', '54')
            .expect(400)
    })
})

Using JavaScript to Check Multiple Checkboxes

I have a form, within it is a table with multiple checkboxes and text input boxes. The checkboxes do not have ids, only different attributes. I want to check off multiple boxes when I run the script in the console. I cannot edit the HTML. This is what I’ve got so far, but I’m not sure how to get it to work, or if it is even possible. Thanks for any help.

function chk () {
  document.querySelector('[name="A"]').checked = true; 
  }
<form>
<table>
    <TR>
         <TD align="left"><INPUT TYPE=CHECKBOX NAME="A">A:</TD>
         <TD align="right"><input type="text" name="effDateTxtA" value="" class="detailstyle"></TD>
    </TR>
 </table>
 </form>

Angular 8+ event stoppropogation

I have a viewChild element which I show/hide by assigning a boolean value to it.

<div #acc class="user-info" [ngClass]="{'showDropdown': accountDropdownService.userDropdownIsVisible}">
  <div class="user-name">
    <div class="color-1 full-name">{{userdata.FirstName}} {{userdata.LastName}}</div>
    <div class="opened-eye-icon color-6__fm icon-icon_visible_off"
         [class]="balanceService.showBalance ? 'icon-icon_visible_off' : 'icon-icon_visible'"
         (click)="balanceService.toggleBalanceVisibility()"></div>
  </div>
  <div class="user-id color-6__fm">{{'General.Id'}}: <span><strong>{{userdata.Id}}</strong></span></div>
</div>

and its .ts file

@ViewChild('acc') public acc: ElementRef;

this.renderer.listen('window', 'click', (e: Event) => {
      if (e.target !== this.acc.nativeElement) {
        console.log('outside');
        console.log(e.target);
      }
    });

I need to hide viewChild element when I clicking outside of it, but when I click on its child elements like user-name or user-id its also understand as an outside click.

How can I prevent this when I’m clickin on div’s children elements?

Call onSelect callback for Air datepicker from Jest unit tests

I am writing a wrapper on top of Air-datepicker in React.js for our component library. I have chosen to pass/override ‘onSelect’ hook while passing the options to Datepicker while instantiating.

While writing the unit test using Jest and react-testing-library, I am not able to invoke onSelect handler through the event mechanism. The steps I am following:

  1. rendered the component.
  2. picked the text input component (a React component) using screen API.
  3. Fired focusIn event on text input, so that date picker will be displayed.
  4. Next, I am trying to select datepicker-cell.
  5. Next I am trying to fire the click event on datepicker-cell.
  6. If I put the breakpoint in onSelect hook, the control never comes to this hook.

Could you please help, how can I solve this issue?

Send Array after Loop

I try to make a list with products that I send to the client, but the res.send gets executed before the loop has finished.

Do you have any suggestions? Async/await doesn’t seem to work

Here is my code:

const Outfits = require("../models/Outfits");
const Products = require("../models/Products");


module.exports = (req, res) => {
    Outfits.find({ outfitId: req.params.id }, async (error1, result) => {
        if (error1) {
            res.status(400).json({
                status: "fail",
            });
        } else {
            let productIds = result[0].productIds;
            let productList = [];
            await productIds.map((e) => {
                Products.find({ id: e }, (error2, product) => {
                    if (error2) {
                        res.status(400).json({
                            status: "fail",
                        });
                    } else {
                        console.log(product);
                        productList.push(product);
                    }
                });
            });
            console.log(productList);
            res.status(200).json({
                status: "success",
                body: productList,
            });
        }
    });
};

Thank you very much!

Hamburger Menu position in React Native

i am trying to move the hamburger menu from left to right in react native. Unfortunately I can’t.
Can anyone help me please …? This is the code:

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { DrawerActions } from '@react-navigation/native';
import pageArticle from "./pages/article";
import pageFeed from "./pages/feed";

const Drawer = createDrawerNavigator();

const MyDrawer = () => {
  return (
    <Drawer.Navigator 
        initialRouteName="Feed"
        screenOptions={{
            drawerPosition: 'right',
        }}
    >
        <Drawer.Screen name="Feed" component={pageFeed}
        
        />
        <Drawer.Screen name="Article" component={pageArticle} />
    </Drawer.Navigator>
  );
}

export default function App() {
  return (  
    <NavigationContainer>
        <MyDrawer />
    </NavigationContainer>
    
  );
}

With the command drawerPosition: ‘right’, I can put the drawer on the right but not the hamburger menu.

Please… Help me…

jalali calendar for YITH Event Tickets for WooCommerce plugin

recently, I am using YITH Event Tickets for WooCommerce for a customer. The problem is my WordPress calendar is Jalali calendar (the WordPress language is Also Persian) but the plugin uses Gregorian calendar in the backend and admin panel, so when I set the date in Jalali type (like : 1400-10-05) every event would be set for 600 years Ago. How can I use the Jalali calendar for the backend?

Thanks in advance.

enter image description here

JavaScript for loop that alternates two constants

I’ve been trying to use a for loop to make a code that alternates between two strings and ends with .toUpperCase , but I’m completely stuck. I’m “able” to do it with an array with two strings (and even so it has a mistake, as it ends with the first string of the array…), but not with two separate constants.
Could anyone offer some help?

function repeteFrases(num) {
  const frases = ["frase um", "frase dois"];
  let result = "";
  for (let i = 0; i < num; i++) {
    result += i === num - 1 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
  }
  return result;
}
console.log(repeteFrases(2));

Using Tone.js to add filters to an existing audio stream

I was able to add filters to an existing audio stream using the biquadfilter but was interested in trying to use Tone.js instead. But I’m having issues connecting everything together. I keep getting a DomException when trying to connect the filter to an audioContext.

function addFilter(fq) {

    var audioCtx = new (window.AudioContext || window.webkitAudioContext);
    var mediaElem = document.getElementById('myAudioElement');

    //Tone.context = audioCtx;
    Tone.context.createMediaElementSource(mediaElem)

    const bqfilter = new Tone.Filter(fq, 'lowpass').toDestination();

    Tone.connect(bqfilter, audioCtx.destination);
    //bqfilter.chain(audioCtx.destination)
});

The error message is just DomException when I try to connect or chain the filter to the audioCtx.destination. This seems to follow most of the other examples I’ve found online so I’m not sure why this is throwing an exception.

Can’t return user total presence.status of Global

I want to retrieve all my users of all guilds where my bot is used at.
What i need is a total(global) of these :

presence?.status == "offline")
presence?.status == "online")
presence?.status == "DND")
presence?.status == "bots")

well what i did is this and it returned 0 :

let userCount = message.client.users.cache.filter(member => member.presence?.status == "offline").size
    console.log("total",userCount)

If i want to return everyone as a total(global) that works normal:

let userCount = message.client.users.cache.size;
console.log("total",userCount)

any idea how to do this? i’m on v13

regards

Loading “many” related models eagerly with a “between” predicate

I have a model with “termStart” and “termEnd” dates. The rows in the table will have disjoint time ranges; that is, there won’t be overlaps. I’ve established a many-to-one relationship successfully, and now I want to do an eager load (a join) to the “many” table with a predicate that picks the row whose start-end range includes the current date. I think I need to do that with something like:

const model1s = parent.getModel1s({
    include: "model2",
    where: // something
});

I know that there’s a between operator, but I cannot find any information on exactly how it works, or how it works when I am checking two dates in the table with a single date in the query (as opposed to checking a single date in the table with a range in the query).

I’m only a few days into using Sequelize so this may be obvious. I’ve been going in circles through the documentation and I can’t find anything. If there’s a way of even supplying a raw SQL predicate fragment, that’d be fine by me; I know how to do it in SQL of course.

A related question is this: is there a way to go through the .getSomethings() method that establishing a many-to-one relationship creates, but do so such that Sequelize knows that the join will involve a single row? In other words, because my date ranges do not overlap, the “between” comparison (however it ends up working) is guaranteed to find either zero or one “model2” rows.

I know I could do this with a separate .findOne() call, but of course I’d prefer to do a single query to get all the model1 instances without having to do separate queries for each one of those.

Filtering an object array with another array

I am having a filtering problem..

objArray is the array that needs to be filtered.
selectedNames is an array that contains the values that I want to find in objArray.
I need to fetch all objects that have one or more values from selectedNames in their “names” property (an array) .

The output I am trying to get is :

let result = [{names:["A","B","C","D"]},
              {names:["A","B"]},
              {names:["A","D"]}
             ]

Here is a simplified version of my code:

let objArray = [{names:["A","B","C","D"]},
                {names:["C","D"]},
                {names:["C","D","E"]},
                {names:["A","B"]},
                {names:["A","D"]}
               ]

let selectedNames = ["A","B"]

result = this.objArray .filter(obj => {
   return this.selectedNames.includes(obj.names)
}


My code seems to work fine if names attribute was a single value and not an array. But I can’t figure out how to make it work on an array.

Any help is more than welcome