Using new collections for each user

I am building an Expense Tracking app using Node.js where all the Income and Costs should get saved in a database.

My idea is to create a new collection for each registered user and save all their income/cost actions in that collection.

The things i would like to consider before writing it are:

  • how do i name the collections
  • Efficiency of this method
  • is it even secure
  • how do i save their data when they login from an another device
  • can two users have the same collection name causing them to save their actions in one collection
  • are there any better ways to do this

What i came up with to solve it was to make a model which takes the given company/user name to create a collection.

const mongoose = require('mongoose');
const bcrypt = require ('bcrypt');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    userName: {
        type: String,
        required: true,
        unique: true
    },
    userPass: {
        type: String,
        required: true
    },
    userEmail: {
        type: String,
        required: true,
        unique: true
    }
}, { timestamps: true });

UserSchema.pre('save', async function (next) {
    try {
        const hashed = await bcrypt.hash(this.userPass, 10)
        console.log('saved user with hashed password.')
        this.userPass = hashed
        next();
    } catch {
        next(error)
    }
})

const User = mongoose.model(userName, UserSchema);

module.exports = User;

And that collection can only be accessed by the one who has the password for that unique name.

So what i would like to ask is: Are there any better ways to do this?

Buefy autocomplete deselect and input issue

I have a Buefy autocomplete field in my project.

<b-field>
    <b-autocomplete
        v-model="client"
        :data="agencyClients"
        field="name"
        @input="setClient"
        :clearable="true"
        open-on-focus
        size="is-small"
    >
    </b-autocomplete>
</b-field>

The v-model property should be the object in form

{id: 10, name: 'AAA'} 

Therefore I use field property in the input which is set to name. This basic set up works well. But if I trigger @input event which looks like

async setClient(clientName) {
    if( clientName ) {
        const client = this.agencyClients.find((item) => item && item.name === clientName);
        if( client ) {
            await this.$store.dispatch(`${this.storeName}/updateClientId`, {clientId: client.id});
            this.client = client;  // Set client as object. 
        }
    }
},

I get and [object] as value in input field. Autocomplete is not able to show client.name value as onload. Why is it so?

The second issue is that with deselect function. It does not trigger @input event. It does not make sence. If I clear the value input event is not triggered? Why?

Can somebody explain me what am I doing wrong? Thanks a lot.

Updating array of objects with recursing function (Mapping replies to comments dynamiclly)

I am receiving a list of comments from a graphql backend in the following format:

[
        {
            "__typename": "Comment",
            "id": "1",
            "userId": "1",
            "postId": "1",
            "parentCommentId": null,
            "content": "test 1"
        },
        {
            "__typename": "Comment",
            "id": "2",
            "userId": "1",
            "postId": "1",
            "parentCommentId": null,
            "content": "this is a comment"
        },
        {
            "__typename": "Comment",
            "id": "34",
            "userId": "1",
            "postId": "1",
            "parentCommentId": "1",
            "content": "reply to test1"
        },
        {
            "__typename": "Comment",
            "id": "35",
            "userId": "1",
            "postId": "1",
            "parentCommentId": "34",
            "content": "nested reply to "reply to test1"nn"
        },
        {
            "__typename": "Comment",
            "id": "36",
            "userId": "1",
            "postId": "1",
            "parentCommentId": "34",
            "content": "test?"
        }
    ]

The comments with parentCommentId === null are the highest level comments, while comments where parentCommentId !== null are replies to a comment where id === parentCommentId

I would like to transform this data structure to something like:

[{
    "__typename": "Comment",
    "id": "1",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "test1",
    "replies": [{
      "__typename": "Comment",
      "id": "34",
      "userId": "1",
      "postId": "1",
      "parentCommentId": "1",
      "content": "reply to test1",
      "replies": [{
        "__typename": "Comment",
        "id": "35",
        "userId": "1",
        "postId": "1",
        "parentCommentId": "34",
        "content": "reply to test1"
      }]
    }]
  },
  {
    "__typename": "Comment",
    "id": "2",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "this is a comment",
    "replies": []
  }
]

I have the following function to do the data transformation:

function formatData(comments: Array < IComment > ) {
  let commentList = Array < IComment > ();

  // add comments without `parentCommentId` to the list.
  // these are top level comments.
  for (let i = 0; i < comments.length; i++) {
    if (!comments[i].parentCommentId) {
      commentList.push({ ...comments[i],
        replies: []
      });
    }
  }

  for (let i = 0; i < comments.length; i++) {
    if (comments[i].parentCommentId) {
      const reply = comments[i];
      mapReplyToComment(commentList, reply);
    }
  }


  return commentList;

  function mapReplyToComment(
    commentList: Array < IComment > ,
    reply: IComment
  ): any {
    return commentList.map((comment) => {
      if (!comment.replies) {
        comment = { ...comment,
          replies: []
        };
      }
      if (comment.id === reply.parentCommentId) {
        comment.replies.push(reply);

        return comment;
      } else {
        return mapReplyToComment(comment.replies, reply);
      }
    });
  }
}

However this only works for one level deep into the object tree. so I am getting the replies of a main comment, but replies to replies are not added to the object.

this is what I am getting now:

[{
    "__typename": "Comment",
    "id": "1",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "test1",
    "replies": [{
      "__typename": "Comment",
      "id": "34",
      "userId": "1",
      "postId": "1",
      "parentCommentId": "1",
      "content": "reply to test1"
      // -- I should have here another node of "replies"
    }]
  },
  {
    "__typename": "Comment",
    "id": "2",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "this is a comment",
    "replies": []
  }
]

Could you please point out what am I doing wrong and provide some explanation?
Thanks in advance

Not able to launch another component in react. passing values as params

I am calling another from current component

<Link to={`/${props.certificate.id}/edit` } >Edit</Link>

in the receiving component I am receiving it using props.

export function EditCertificate(props: any)

then I am accepting id as

const {id} = props.match.params;

so in the url below is coming but EditCertificate component is not getting launched.

http://localhost:4200/934108e0-ca73-4837-bbf2-26482ece1cb6/edit

in the route I have defined below.

  <SecureRoute path=":id/edit">
            <EditCertificate id={':id'} />
        </SecureRoute>

what mistake I am doing?

CSS Modules not working after upgrading nodejs version

I upgraded the version of Node JS on the project from v12 to v14 and with that some of the packages including laravel-mix.Through-out the project there are these css modules “:global(selector)” being used , that after updating are not working.

I tried adding css-loader as a module in webpack.mix.js:

module: {
        rules: [
            {
                test: /.css$/,
                use : [
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                        }
                    }
                ]
            }]} // there are some other babel rules as well.

After running npm run watch and it compiles it shows this error:

ERROR in ./resources/css/fontello.css (./node_modules/laravel-mix/node_modules/css-loader/dist/cjs.js??clonedRuleSet-7[0].rules[0].use[1]!./node_modules/postcss-loader/dist/cjs.js??clonedRuleSet-7[0].rules[0].use[2]!./node_modules/css-loader/dist/cjs.js??clonedRuleSet-23[0].rules[0].use[0]!./resources/css/fontello.css)
  Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):  
  SyntaxError

  (1:1) C:UsersosmanDesktopProjectsmyhomeresourcescssfontello.css Unknown word

  > 1 | // Imports
      | ^
    2 | import ___CSS_LOADER_API_NO_SOURCEMAP_IMPORT___ from "../../node_modules/css-loader/dist/runtime/noSourceMaps.js";
    3 | import ___CSS_LOADER_API_IMPORT___ from "../../node_modules/css-loader/dist/runtime/api.js";

There are 14 errors exactly the same as this that appear, just the path ./resources/css/fontello.css changes.

In the browser console the error appears like this:

Uncaught Error: Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
SyntaxError

(1:1) C:UsersosmanDesktopProjectsmyhomeresourcescssthemeindex.css Unknown word
[1m[31m>[39m[22m[90m 1 | [39m// Imports
 [90m   | [39m[1m[31m^[39m[22m
 [90m 2 | [39mimport ___CSS_LOADER_API_NO_SOURCEMAP_IMPORT___ from [32m"../../../node_modules/css-loader/dist/runtime/noSourceMaps.js"[39m[33m;[39m
 [90m 3 | [39mimport ___CSS_LOADER_API_IMPORT___ from [32m"../../../node_modules/css-loader/dist/runtime/api.js"[39m[33m;[39m

Any help would be appreciated.

Dependent dropdown for dynamic form not working

Hello Everyone here I am trying to assign a dependent dropdown to the current dynamic form i.e. if I select the cost center it will load the cost center dependent child Sub Head data from DB.
It is working fine for a single row but when I add another row it was not working

please help

when I work with single row it will work fine

enter image description here

but when i click Add More and do same with other row it will not work

enter image description here

this is my HTML code


<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5 - onChange event using ajax dropdown list</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
                    <table class="table" id="dynamicTable12">
                <tr>
                    <th scope="col"width="250" >Ledger</th>
                    <th scope="col" width="250">Costcentre</th>
                    <th scope="col" width="250">Sub Head</th>
                    <th scope="col" width="75">Dr/Cr</th>
                    <th scope="col" width="175">Amount</th>
                </tr>
                <tr>
                <td> <select name="addmore[0][ledger]" id="" class="form-control js" required="required">
                <option value="">--Please select one--</option>
                @foreach ($bud as $buds)
                <option value="{{$buds->id}}">{{$buds->name}}</option>
                @endforeach
                </select></td>  
                <td>  <select name="addmore[0][project]" class="form-control js" id="state" required="required">
                 <option value="">-- Select Project --</option>
                   @foreach ($countries as $key => $value)
                    <option value="{{ $key }}">{{ $value }}</option>
                    @endforeach
                  </select>
    
                   </td>

                  <td>  <select name="sub" class="form-control">
                    <option>-- Sub Head--</option>
                    </select>
                    </td>
                    <td><select name="addmore[0][cr_dr]" id="" class="cr_dr form-control" required="required">
                    <option value="">----</option>
                    <option value="Dr">Dr</option>
                    <option value="Cr">Cr</option>
                    </select></td>  
                    <input type="hidden" value='0' name='addmore[0][banks]' >
                    <td><input type="number" name="addmore[0][amount]" placeholder="Amount" class="txt form-control" required="required"/></td>  

                    <td><button type="button" name="add" id="add12" class="btn btn-success">Add More</button></td> 
             </tr>
            </table>

And this is Javascript code

 <script type="text/javascript">
                        $(document).ready(function() {
                        
  $(document.body).on("change.select2", "#state",function () {
      var id_country = $(this).val();
      var token = $("input[name='_token']").val();
      $.ajax({
          url: "<?php echo route('select-ajax') ?>",
          method: 'GET',
          dataType: 'json',
          data: {id_country:id_country, _token:token},
          success: function(data) {
            $("select[name='sub'").html('');
            $("select[name='sub'").html(data.options);
          }
      });
  });
                        });
</script>
<script>


let initializeSelect2 =  function() {
  $('.js').select2();
}

var i = 0;
$("#add12").click(function(){
    ++i;
    $("#dynamicTable12").append('<tr><td><select name="addmore['+i+'][ledger]" id="" class="form-control js" required="required"><option value="">--Please select--</option>@foreach($bud as $iit_bank)<option value="{{$iit_bank->id}}">{{$iit_bank->name}}</option>@endforeach</select></td> <td> <select id="state" class="form-control js" name="addmore['+i+'][project]" required="required"><option value="">--select--</option>@foreach($buud as $iit_bank)<option value="{{$iit_bank->id}}">{{$iit_bank->name}}</option>@endforeach</select></td> <td> <select name="sub" class="form-control"><option>-- Sub Head--</option></select></td><td><select name="addmore['+i+'][cr_dr]" id="" class="cr_dr form-control" required="required"><option value="">--select--</option><option value="Dr">Dr</option><option value="Cr">Cr</option></select></td><td><input type="number" name="addmore['+i+'][amount]" placeholder="Amount" class="txt form-control" required="required"/></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
    
    initializeSelect2()
});
$(document).on('click', '.remove-tr', function(){  
     $(this).parents('tr').remove();
}); 



$(document).ready(function() {
    initializeSelect2()
});


</script>

And also I want to name the Subhead with an array but it was not working fine

Binance API, how to read total balance value in BTC (or USD), or how to read earn wallet details

Using Binance API, I want to get my total account balance in BTC (or USD)

I am able to get the spot wallet balance by querying /api/v3/account endpoint.

In my case, the total balance is the SUM of spot wallet + earn wallet.

const totalBalance = spot + earn

With only spot, I am not able to calculate totalBalance nor earn.

Using the Binance API, how can I get the totalBalance or earn?

My math.pow is return NaN when I call it on an array with numerical values. How do I get the square of an array element

I have a function with an array of numbers, I want to square it but I want them in the array box like [4,9,16] Each time i try to do that, it throws back a NAN output in the console. The numbers come back listed as in a straight line.

  digit = (num) => {
let digits = String(num).split('')
.map(Number);      
for(let i = 0; i < digits.length;
i++){
let square = Math.pow(digits,2);
console.log(square);
}
};
digit(234);

output : NaN

digit = (num) => {
let digits = String(num).split('')
.map(Number);

     
for(let i = 0; i < digits.length;
i++){
let square = Math.pow(digits[i],2);
console.log(square);
}
};
digit(234);

output : 4
9
16

Is it possible to have my output as [4,9,16]?

Django, Python: Can’t filter products with passing values true the get request and order the products

I’m trying to filter some products and order the filtered products by price ascending and descending.

This is my code in the view:

def is_valid_queryparam(param):
    return param != '' and param is not None

def filter(request):
  if request.GET:
      price_min = request.GET.get('priceMin')
      price_max = request.GET.get('priceMax')
      sort_by = request.GET.get("sort", "l2h")

      if is_valid_queryparam(price_min):
          if sort_by == "l2h":
              products = Product.objects.filter(price__gte=price_min).order_by('price')
          elif sort_by == "h2l":
              products = Product.objects.filter(price__gte=price_min).order_by('-price')
          paginator = Paginator(products, 9)
          page = request.GET.get('page')
          paged_products = paginator.get_page(page)
          product_count = products.count()

      if is_valid_queryparam(price_max):
          if sort_by == "l2h":
              products = Product.objects.filter(price__lte=price_max).order_by('price')
          elif sort_by == "h2l":
              products = Product.objects.filter(price__lte=price_max).order_by('-price')
          paginator = Paginator(products, 9)
          page = request.GET.get('page')
          paged_products = paginator.get_page(page)
          product_count = products.count()
  else:   
      products = Product.objects.all().order_by('price')
      paginator = Paginator(products, 9)
      page = request.GET.get('page')
      paged_products = paginator.get_page(page)
      product_count = products.count()

  context={
      'products': paged_products,
      'product_count': product_count,
  }
  return render(request, 'store.html', context)

If I try to filter based on the min and max price it works, but when I’m trying to sort or if there is no filter apply I get this UnboundLocalError:

UnboundLocalError at /store/
local variable ‘paged_products’ referenced before assignment
Request Method: GET
Request URL: http://127.0.0.1:8000/store/?sort=h2l
Django Version: 3.1
Exception Type: UnboundLocalError
Exception Value:
local variable ‘paged_products’ referenced before assignment
Exception Location: C:Usersstoreviews.py, line 299, in filter

I researched django documentation, google and SO but I did not find a solution.
I have tried to rearrange the code, exclude ‘sort’ from request.GET params and no success.

Construct a new string where each number between colons is a valid number from the array given

Given a string nums, which contains only digits, and an array of numbers predefinedNumbers,
add colons in nums to construct a new string, where each number between colons is a valid number from predefinedNumbers.
Return all possible strings.

EX:
nums = “143163421154143”
predefinedNumbers = [“21154”, “143”, “21154143”, “1634”, “163421154”]

makeNumSentences(nums, predefinedNumbers)

Output:
[
“:143:1634:21154:143:”,
“:143:163421154:143:”,
“:143:1634:21154143:”
]

CSS Sliding Animation for Background Position on click

I have the following code that animates the background-position property so it “slides” to a different color afterwards. My problem currently is how to reverse it. Most of the examples I’ve seen is around hover; this one though is from a context of a click event. Any ideas how I can reverse the animation on re-toggling it?

Invalid escape in regex – unable to convert from regex to html input pattern [duplicate]

I need help to make the html input pattern to work correctly with the following regexp:

/^([0-9]+(.[0-9]*[1-9]|);)*[0-9]+(.[0-9]*[1-9]|)+$/mg

This expression only allow a infinite group of positive numbers, with or without a decimal fraction marked with a point, separated by semicolon. For example:

23;23.3;444

I tried:

document.querySelectorAll("input")[0].pattern="^([0-9]+(.[0-9]*[1-9]|);)*[0-9]+(.[0-9]*[1-9]|)+$";

But in the html pattern, allows:

23;23.3;444;44-4;44,4

Using JS works perfectly:

regex = /^([0-9]+(.[0-9]*[1-9]|);)*[0-9]+(.[0-9]*[1-9]|)+$/mg;
regex.test("541.4;4;3;3.3;33;33;45.5;443;4");  //true
regex.test("541.4;4;3;3.3;33;33;45.5;4-43;4"); //false

Any ideas how to fix this html pattern? Thank you.