Is there any way to show only cities which are the part of waypoints of the road directions in angular google map

I am working on google map using angular. I have used direction api and created roadways.
My requirement was to remove cities from the map by showing only state name. I achieved that, but now the issue is the cities which are the part of waypoints are also not displaying as shown in the image.

path without city name

some portions of my code while setting up the google map is given below.

 options: google.maps.MapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 6,
styles: [

  {
    elementType: 'geometry',
    stylers: [
      {
        color: '#f5f5f5',
      },
    ],
  },
  {
    elementType: 'labels.icon',
    stylers: [
      {
        visibility: 'off',
      },
    ],
  },
  {
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#616161',
      },
    ],
  },
  {
    elementType: 'labels.text.stroke',
    stylers: [
      {
        color: '#f5f5f5',
      },
    ],
  },
  {
    featureType: 'administrative.land_parcel',
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#bdbdbd',
      },
    ],
  },
  {
    featureType: 'poi',
    elementType: 'geometry',
    stylers: [
      {
        color: '#eeeeee',
      },
    ],
  },
  {
    featureType: 'poi',
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#757575',
      },
    ],
  },
  {
    featureType: 'poi.park',
    elementType: 'geometry',
    stylers: [
      {
        color: '#e5e5e5',
      },
    ],
  },
  {
    featureType: 'poi.park',
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#9e9e9e',
      },
    ],
  },
  {
    featureType: 'road',
    elementType: 'geometry',
    stylers: [
      {
        color: '#ffffff',
      },
    ],
  },
  {
    featureType: 'road.arterial',
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#757575',
      },
    ],
  },
  {
    featureType: 'road.highway',
    elementType: 'geometry',
    stylers: [
      {
        color: '#dadada',
      },
    ],
  },
  {
    featureType: 'road.highway',
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#616161',
      },
    ],
  },
  {
    featureType: 'road.local',
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#9e9e9e',
      },
    ],
  },
  {
    featureType: 'transit.line',
    elementType: 'geometry',
    stylers: [
      {
        color: '#e5e5e5',
      },
    ],
  },
  {
    featureType: 'transit.station',
    elementType: 'geometry',
    stylers: [
      {
        color: '#eeeeee',
      },
    ],
  },
  {
    featureType: 'water',
    elementType: 'geometry',
    stylers: [
      {
        color: '#c9c9c9',
      },
    ],
  },
  {
    featureType: 'water',
    elementType: 'labels.text.fill',
    stylers: [
      {
        color: '#9e9e9e',
      },
    ],
  },
],};
this.map = new google.maps.Map(document.getElementById('googleMap'), {
  ...this.options,
  center: this.waypoints[0].location,
});

So I want a solution where I can show only the cities which are the part of the road path i.e the waypoints.

Trying to resolve javascript error “TypeError: viral[i].substring is not a function”” [closed]

Can someone please tell me what is wrong with this code?

//Choosing an option in dropdown will give random song result
var viral = [(getColumn("Viral 50 USA", "Position"))];
var filteredList = [];
onEvent("dropdown1", "input", function( ) {
  tenFilter();
  setProperty("text_area1", "text", filteredList);
});
//Filters songs by Top 10
function tenFilter() {
 for (var i = 0; i < viral.length; i++) {
    var top10 = viral[i].substring(1, 10);
    if (top10 >= 10) {
      appendItem(filteredList, viral[I]);
    }
  }
  return filteredList;
}

//
“`

I get this error in the debug console:

ERROR: Line: 11: TypeError: viral[i].substring is not a function"

React.js inserting multiple states into one main state

I’m trying to make an app where an ‘Owner’ can have multiple ‘cars’, I have my App.js file where the Owner enters there name and can enter there car details (‘Car name’ and ‘Car Type’), a Owner can have multiple Cars, and when they click ‘Add car entry’ a Component where they enter there car details called ‘OwnersCars’ is repeated. Like so

With one 'OwnersCars' component to With two 'OwnersCars' component

If an owner fills out the input boxes in this component (For X amount of cars) then clicks ‘Save Owner’ i want the owner aswell as a list of all there cars to be saved into one State.

Currently i have my app.js file like this (count is used to know the number of OwnersCars divs)

import './App.css';
import React, {useState, useRef} from 'react';
import OwnersCars from './ownersCars';

function App() {

  const [count, setCount] = useState(1) 

  const [OwnerInput, SetOwnerInput] = useState({
    id: "",
    Name: "",
    cars: []

});

const [newCarInput, SetnewCarInput] = useState({
    id: "",
    Type: "",
    CarName: ""
    });


  const removeDiv = () => {
    //console.log('swnag')
    setCount(count - 1)
  }

  const repeatDiv = () => {
      //console.log('swnag')
      setCount(count + 1)
  }

  const displayCarInput = (e) => {
    //console.log(count, "<--key")
    return ( ([...Array(count)].map((e, i) => <OwnersCars onAddNameCar={addNewCarNameHandler} onAddTypeCar={addNewCarTypeHandler}></OwnersCars> )))
  }

  const displayRemove = (e) =>{
    if (count > 1) {
        return (<button className='removeAnimalButton' onClick={removeDiv}> <dt> Remove Last Animal Entry</dt></button>)
    }
  }

  const NameHandler = (e) => {
    //console.log(e.target.value)
    SetOwnerInput((prevState) => {
        return { ...prevState, Name: e.target.value };
      });
  }

  const submitHandler = (event) => {
    event.preventDefault();
    const value = Math.random().toString()
    const OwnerData = {
        id: value,
        Name: OwnerInput.Name,
        cars: [newCarInput]

    };

    console.log(OwnerData, "<--- ownerdata with cars data");
  }

  const addNewCarNameHandler = (values) => {
    //console.log(values, "<---5")
    SetnewCarInput((prevState) => {
        return { ...prevState, CarName: values };
      });

  };

  const addNewCarTypeHandler = (values) => {
    //console.log(values, "<---5")
    SetnewCarInput((prevState) => {
        return { ...prevState, Type: values };
      });

  };



  return (

    <div>
    <div>
        <div>
            <label for="exampleInputPassword1"></label>
            <button onClick={submitHandler} ><dt>Save Owner</dt></button>
        </div>
    </div>
    <hr/>
    <div className="wrapper">

            <div class="new-owner-div">
                <h5>Owner</h5>
                    <hr/>
                      <form>
                      <div>
                            <input type="name" id="exampleInputClinic" placeholder="Owner Name"  onChange={NameHandler}/>
                      </div>
                </form>
            </div>

            <div class="new-owner-div-2">
                <h5>Owners Cars</h5>
                    <hr/>
                        {displayCarInput()}
                        <div>
                            <button onClick={repeatDiv}> <dt> Add Car Entry</dt></button>
                            {displayRemove()}
                        </div>
            </div>

    </div>

</div>

  );
}

export default App;


and i have my ownersCars.js file with the OwnersCars component like this


import React, {useState, useRef} from 'react';

function OwnersCars(props) {


    const CarNameHandler = (e) => {
        console.log(e.target.value)
        props.onAddNameCar(e.target.value)
    }

    const CarTypeHandler = (e) => {
        console.log(e.target.value)
        props.onAddTypeCar(e.target.value)
    }

    return(
        <div>
            <div>
                    <div>
                        <h3>Car name</h3>
                        <span></span>
                        <h3>Type</h3>
                    </div>
                    <div>
                        <div>
                            <input placeholder="Car Name" onChange={CarNameHandler}/>
                        </div>
                        <span class="span1-box"></span>
                        <div class="height">
                            <input class="input-box-OA-2"  placeholder="Car Type" onChange={CarTypeHandler}/>
                        </div>
                        <span class="span1-box"></span>
                    </div>
                </div>
        </div>
    )

} 

export default OwnersCars

but when i click save user it only saves the latest car entry!

Would anyone be able to help?

Sorry for the mess and lack of css i removed a bunch of things from the original code so it was easier to follow on StackOverflow. Also im fairly new to react so im sure theres alot of things that need to be changed for this to work.

Uncaught TypeError: $(…).dataTable is not a function dataTables.fnSetFilteringDelay

Getting this error, “Uncaught TypeError: $(…).dataTable is not a function” with one of my data tables. The error is happening on this line “$(“table#metadata_index”).dataTable”. Any ideas how to solve it? I tried adding jQuery instead of $ “jQuery(“table#metadata_index”).dataTable but this did not work.

index.html.erb

<% content_for :javascripts do %>
  <%= javascript_pack_tag "jquery.dataTables.columnFilter-1.5.6": 'reload' %>
  <%= javascript_pack_tag "dataTables.fnSetFilteringDelay": 'reload' %>

  <script type="text/javascript">
    $(document).ready(function() {
        console.log($("table#metadata_index"));
      var last_search = [];

      function openCloseDetails(tableRow, remoteURL) {
      if ( $(tableRow).hasClass("open_row") )
      {
        $(tableRow).removeClass("open_row");

        var nRemove = $(tableRow).next()[0];
        $(nRemove).fadeOut('fast', function() {
          nRemove.parentNode.removeChild( nRemove );
          oTable.fnClose( tableRow );
        });
      }
      else
      {
        $.ajax({
            mode: "abort",
            dataType: "html",
            url: remoteURL + "?basic=true",
            success: function(data) {
              var colspan = $("td", tableRow).length

              var newRow = $("<tr style='display: none'/>");
              var col = $("<td/>");
              col.attr('colspan', colspan);
              col.addClass("inset_box_shadow");
              newRow.append(col);
              $(tableRow).addClass("open_row");

              $(col).html(data);

              $(tableRow).after(newRow);

              $(newRow).fadeIn('fast');
            }
        });
      }
    }

      var oTable = $("table#metadata_index").dataTable({
        "sDom": '<"H"<Ci>r<"filter_group"p>>t<"F"l<"right_align"p>',
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bAutoWidth": false,
        "oColVis": {
          "aiExclude": [ 0 ],
          "buttonText": "&nbsp;",
          "sAlign": "left",
          "sSize": "css",
        },
        "oLanguage": {
          "sSearch": "",
          "oPaginate": {
            "sPrevious": "<",
            "sNext": ">",
          },
        },
        "bStateSave": true,
        "sCookiePrefix": "metadata_index",
        "bServerSide": true,
        "bProcessing": true,
        "sAjaxSource": "<%= analyses_element_metadata_path %>.json",
        "fnServerData": function( sSource, aoData, fnCallback ) {
          last_search = aoData;
          $.getJSON( sSource, aoData, fnCallback );
        },
        "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
            $(nRow).click(function() {
              
              /*
              ** differentiate between change and non-change objects
              ** change uses change_request_id and non-change uses respective id's
              ** change_request_id needs to be in aData[1]
              */

              var href = false;
              href = $(nRow).find('a').attr("href")

              if(href){
                openCloseDetails(this, href + '');  
              }
              
            });

            $(nRow).find("a").click(function(event) {
              event.stopPropagation();
            });

            return nRow;
          },
      });
      oTable.columnFilter({
        sPlaceHolder: "head:after",
      });
      oTable.fnSetFilteringDelay();

      // Number of relative pages in the pagination control.
      $.fn.dataTableExt.oPagination.iFullNumbersShowPages = 7;

      $("#export_tsv").click(function() {
        query = [];
        // Flatten last_search parameters, please.
        for (item in last_search) {
          item_contents = last_search[item];
          query.push(item_contents['name'] + "=" + item_contents['value']);
        }

        window.location.href = "<%= export_analyses_element_metadata_path(:format => 'tsv') %>?" + query.join("&");
      });

      $("#delete_items").click(function() {
        query = [];
        // Flatten last_search parameters, please.
        for (item in last_search) {
          item_contents = last_search[item];
          query.push(item_contents['name'] + "=" + item_contents['value']);
        }

        var result = confirm("Really delete all items matching the current set of filters?nThis action cannot be undone.");
        if (result == true) {
          $("#shade").show();
          $.ajax({
            type: "DELETE",
            url: "<%= delete_filtered_items_analyses_element_metadata_path %>",
            data: query.join("&"),
            success: function(redirect_href) {
              $("#shade").hide();
              window.location.href = redirect_href;
            }
          });
        }
      });
    });
  </script>

<% end %>

<% content_for :crumbs do %>
  <li><%= link_to("Analysis", analyses_path) %></li>
  <li class="last"><%= link_to "Metadata", analyses_element_metadata_path %></li>
<% end %>

<% content_for :title do %>
  Element Metadata
<% end %>

<div class="action_heading">
  <div class="table_title">
    <h1>
      <%= yield :title %>
    </h1>
  </div>
  <ul class="dictionary-actions">
      <% if @can_perform_create_element_metadata == true %>
        <li>
          <%= link_to( raw("#{image_tag('new.png')} Create New Element Metadata"), url_for(:action => :new)) %>
        </li>
      <% end %>
      <% if  @can_perform_import_element_metadata %>
        <li>
          <%= link_to raw("#{image_tag('import.png')} Import Metadata"), import_analyses_element_metadata_path %>
        </li>
      <% end %>
      <% if  @can_perform_delete_element_metadata %>
        <li>
          <%= link_to raw("#{image_tag('delete.gif')} Delete Records (as filtered)"), "javascript:void(0);", :id => "delete_items" %>
        </li>
      <% end %>
    <li>
      <%= link_to raw("#{image_tag('export.png')} Export TSV (as filtered)"), "javascript:void(0);", :id => "export_tsv" %>
    </li>
  </ul>
</div>

<table cellpadding="0" cellspacing="0" class="display" id="metadata_index">
  <thead>
    <% 2.times do %>
      <tr>
        <% ElementMetadata::table_view[:columns].each do |column| %>
          <th><%= column[:name] %></th>
        <% end %>
      </tr>
    <% end %>
  </thead>
  <tfoot></tfoot>
  <tbody>
    <td colspan="<%= ElementMetadata::table_view[:columns].size + 1 %>">
      <center>
        Loading...
      </center>
    </td>
  </tbody>
</table>

<div id="shade" style="display:none;">
  <div id="shade_wait">
    Working <%= image_tag("bigspinner.gif") %>
  </div>
</div>

Cypress: Add cookie to external api from localhost backend

I have an external api deployed to a dev server and a frontend app running on localhost. I need to attach the cookies I get from logging in, to both my localhost and external API domain.

I can see the cookies are indeed there using cy.getCookies({domain: null}), however all external API calls within the react app happen without the cookies. From what I can see, you can only add cookies to the baseUrl requests, but I want to run my tests against a deployed backend (so developers don’t need to have a running instance of a local backend, which is whats currently working fine as they are both on localhost)

cy.setCookies(name, value, {domain: localhost}) 
cy.setCookies(name, value, {domain: external_api_domain}) 

React: React-Redux: Redux-Thunk: Memory Leak on Unmounted Component

Im going to formulate this question as best I can because this is very confusing. I am using redux for my applications state. and I am using redux-thunk to handle all of my async api calls to the database.

I am using redux-thunk to handle my async POST api call to the database to add data. I have a parent component and a nested component. The parent component contains my data grid which is the AG React Data grid. I am switching from my parent component that contains my data grid, to the component that contains the form I will use to input data to be stored to the database. Once the async call is finished I want to route back to the original view that contains the grid (The grid, and the input form are nested into the Parent component, and Im using react-router to switch between the two views)

Once the async call is dispatched using a thunk, the app calls history.goBack() before the action being dispatched is actually complete, as it should in an async call. The issue is it results in these two errors when routing back to the original view.

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Uncaught (in promise) TypeError: rowData.map is not a function

How am I able to make sure that the action is completed inside the thunk code, so that the my component re-renders properly.

Parent Component code

    const store = configureStore();
  const dispatch = useDispatch();

  // selects the proper data from the redux store, this variable is used as row data for 
  // AG Grid

  const events = useSelector((state: AppState) => state.events.list);

  const { path, url } = useRouteMatch();
  const history = useHistory();

  const [showBackBtn, setShowBackBtn = () => showBackBtn] = useState(false);

  const goToAddEvent = () => {
    history.push(`${url}/add-event`);
    setShowBackBtn(true);
  };

  const backBtn = () => {
    history.goBack()
    setShowBackBtn(false);
  }

  const columns = [
    { field: "eventName", headerName: "Event name" },
    { field: "eventDate", headerName: "Event Date" },
    { field: "location", headerName: "Location" },
    { field: "startTime", headerName: "Start Time" },
    { field: "endTime", headerName: "End Time" },
  ];

  //gets initial data, saves to the redux store
  useEffect(() => {
    const doGetEvents = async () => {
      dispatch(getEventsAsyncFromDB());
    };
    doGetEvents();

    //setShowBackBtn(!showBackBtn);
  }, [dispatch, store]);

Code for the form input component

const AddEventComponent = () => {

    const dispatch = useDispatch();
    const history = useHistory();

  const addEvent = (event: any) => {
    event.preventDefault();
    let eventData: Event = {
      eventName: event.target[0].value,
      location: event.target[1].value,
      eventDate: event.target[2].value,
      startTime: event.target[3].value,
      endTime: event.target[4].value,
    };

    dispatch(addEventAsyncToDB(eventData));
    history.goBack();
  };

Redux Thunk code that calls the api to add data to the database

export const addEventAsyncToDB = (event: Event) => {
  return async (dispatch: any) => {
    dispatch(addingEventToDb);
    return await addEvent(event).then((res) => {
        dispatch(addedEventToDBAction(res?.data));
    });
  };
};

And finally here is the code that is making the API call

export const addEvent = async (event: Event) => {
    try{
        const res = await axios.post(`${baseURI}/Events`, event);
        return res;
    }
    catch(e){
        console.log(e);
    }
}

Again the API call is successful, the issue is the history.goBack() line is called before the actual API call is finished processing resulting in the errors above. Please bear with me, this is the best way I can form this question

condensing JavaScript import localStorage

Below is the code that I came up with to import the values of a key in localStorage and supply each value the key holds into a function. Being that I’m VERY new to JavaScript, I was wondering if there’s a better way to do what I did below and still provide the same outcome? Without further ado, here is the code.

function importStorage() {
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);             // This references the key
        const values = localStorage.getItem(key)     // This pulls the values associated
        const newValues = values.slice(2, -2)        // This removes this ( and this ) 
        const finalValues = newValues.split("', '")  // This then splits the string
        newBill(finalValues[0], finalValues[1], finalValues[2])
    }
}

Is there a better way?

React Native: Context Provider Retaining Value Even After Unmount

I am building form validation for my project and I decided to use context to leverage the Provider/Consumer pattern. I have two main components: ValidatedForm, and ValidatedAny

To save you time, I won’t include the full solution, just the relevant bits:

ValidatedForm.tsx

const ctx = React.CreateContext<>({});

export { ctx as ValidatedFormContext };

export default function ValidatedForm(props: IValidatedFormProps) {
  const [validatorState, setValidatorState] = useState<ValidatorState>(DEFAULT_VALIDATOR_STATE);

  /** ... omitted ... **/

  const addField = (name: string, valid: boolean, yOffset: number) => {
    if(validatorState.fields[name]) {
      // This warning is being triggered after second mount of this component and its children
      console.warn(`A field with the name ${name} already exists in this form`);
      return;
    }

    const newState: ValidatorState = JSON.parse(JSON.stringify(validatorState));
    validatorState.fields[name] = {
      valid,
      yOffset,
    };

    setValidatorState(newState);
  }

  useEffect(() => {
    return () => setValidatorState(DEFAULT_VALIDATOR_STATE);
  }, []);

  /** ... omitted ... **/

  return <ctx.Provider value={{
    addField,
    /** ... omitted ... **/
  }}>
    {props.children}
  </ctx.Provider>
}

and the child component, ValidatedAny.tsx

export default function ValidatedAny(props: IValidatedAnyProps) {
  const ctx = useContext(ValidatedFormContext);

  /** ... omitted ... **/

  const onLayout = ({nativeEvent}: LayoutChangeEvent) => {
    if(isReady.current) {
      ctx.updateFieldOffsetY(props.name, nativeEvent.layout.y);
    } else {
      isReady.current = true;
      ctx.addField(props.name, validate(), nativeEvent.layout.y);
    }
  }

  const renderedChildrenCount = React.Children.toArray(props.children).length;

  if (renderedChildrenCount !== 1) {
    console.error(
      'ValidatedAny must have extactly one child component rendered at any one time, instead got ',
      renderedChildrenCount
    );
  }

  const childrenWithProps = React.Children.map(props.children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { onLayout });
    }

    return child;
  });

  return <>{childrenWithProps}</>;
}

My expectation is that when this component is unmounted, and then mounted again, validatorState would have the value of DEFAULT_VALIDATOR_STATE.

The first time the component is mounted, it works fine, but every subsequent time it triggers the warning statement in the addField function.

As you can see I added cleanup function via useEffect that does resets state on unmount, but that still didn’t help.

I suspect this has to do with closure, but I may be wrong. I am hoping the great people of stackoverflow can enlighten me on what I am missing here because I am pulling out my hair and I don’t have much of that left. Lol.

how to make my image draggable to observe while zoomed in [duplicate]

it is quite hard to explain in words so I brought a gif animation

enter image description here

As shown above, i wish i could zoom my image in and drag to move around and show or observe other part of pictures to show visitors better view of images of arts.

I recorded my desktop to film this and program that I used is image viewer installed in window 10 default.

i am currently making website for artists to display their art works
i am using react-typescript

if there are certain keywords to google it, please leave on the comments below

thank you

What’s the fastest way to extract number from string? [closed]

I tested these 2 methods:

var name = 'circle 1'

var start = performance.now();

for (i = 1; i < 1000000; i++) {
  parseInt(name.match(/d+/))
}

console.log(performance.now() - start)
// result: 569.2...

var start = performance.now();

for (i = 1; i < 1000000; i++) {
  name.split(' ')[1]
}

console.log(performance.now() - start)
// result: 387.5...

Is there any faster method to get integer from string? I can format the input in any way to achieve speed; but it must contain some letters.

Populate with mongoose-paginate-v2

I’m trying to populate with mongoose-paginate-v2 following its documentation but at the moment it doesn’t send me any error but it doesn’t accomplish the goal either.

My code is the following:

    const options = {
        page: page,
        limit: limit,
        collation: {
          locale: 'es',
        },
        populate: 'user'
      };

const data = await CreditSale.paginate({}, options );

And my main model is this:


const CreditSaleSchema = Schema (
  {
    creditSaleId:{
        type: Number,
        unique: true
    },
    saleId:{
        type: Schema.Types.ObjectId,
        ref:'Sale',
        required: [true, 'El ID de Venta es Obligatorio']
    },
    clientId:{
        type: Schema.Types.ObjectId,
        ref:'Client',
        required: [true, 'El Cliente es obligatorio']
    },
    user:{
        type: Schema.Types.ObjectId,
        ref:'Users',
        required: [true, 'El Usuario es obligatorio']
    },
    subtotal: {
        type: Number,
        default: 0,
        required: [true, 'El Subtotal es obligatorio']
    },
    total: {
        type: Number,
        default: 0,
        required: [true, 'El Total es obligatorio']
    },
    outstandingBalance:{
        type: Number,
        required: [true, 'El Saldo pendiente es obligatorio'],
        default:0
    },
    creditTerm:{
        term:{
            type: String,
            default: 0,
            required: [true, 'El Plazo de Crédito es obligatorio']
        },
        comments:{
            type: String,
            maxlength: 120,
        }  
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
  }  
);

And these the other two models that I try to call with populate:

User:

const UserSchema = Schema (
  {
    username: {
        type: String,
        maxlength:50,
        required: [true, 'El Nombre de Usuario es obligatorio'],
        unique: true
    },
    name: {
        type: String,
        maxlength:50,
        required: [true, 'El Nombre es obligatorio']
    },
    lastName: {
        type: String,
        maxlength:50,
        required: [true, 'El Apellido es obligatorio']
    },
    mail: {
        type: String,
        required: [true, 'El Correo es obligatorio'],
        unique: true
    },   
    password: {
        type: String,
        required: [true, 'La Contraseña es obligatorio']
    },
    status: {
        type: Boolean,
        default: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
  }  
);

Sales Model:

const SaleSchema = Schema (
  {
    saleId: {
        type: Number,
        unique: true
    },
    user:{
          type: Schema.Types.ObjectId,
          ref:'Users',
          required: [true, 'El Usuario es obligatorio']
      },
    clientId:{
        type: Schema.Types.ObjectId,
        ref:'Client',
        required: [true, 'El Cliente es obligatorio']
    },
    notes: {
        type: String,
        maxlength:200,
    },
    subtotal: {
        type: Number,
        default: 0,
        required: [true, 'El Subtotal es obligatorio']
    },
    discount: {
        type: Number,
        default:0
    },
    tax: {
        type: Number,
        default:0
    },
    totalBeforeTax: {
        type: Number,
        default: 0,
        required: [true, 'El Total sin Impuestos es obligatorio']
    },
    total: {
        type: Number,
        default: 0,
        required: [true, 'El Total es obligatorio']
    },
    paymentType: {
        type: String,
        required: true,
        enum: ['CASH', 'CREDIT', 'TRANSFER'] 
    },
    creditTerm:{
        term:{
            type: String,
            default: [true, 'El Plazo es obligatorio en caso de compras a Crédito']
        },
        comments:{
            type: String,
            maxlength: 400,
        }  
    },
    pendingDebit: {
        type: Number,
        default: 0,
        required: [true, 'El Adeudo Pendiente es obligatorio']
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    status: {
        type: Boolean,
        default: true,
        required: [true, 'El Estatus es obligatorio']
    }
  }  
);

For now I am trying to make the population with a model and it does not work. I require popular with more models but I would like to know how to achieve it.

Thanks.

How to assign the response data of axios Post or fetch Post to a variable [duplicate]

How can I save or assign the response body of a Post Method? The dataToken variable returns undefined after console log

let dataToken;;

async function getToken () {
    return axios.post(API_BASE_URL, data, {
     headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
     }
    })
    .then(response => dataToken = response)
    .catch(error => {
      console.log(error);
      return Promise.reject(error);
    });
  }

  getToken()

console.log(dataToken)

enter image description here

Java Problem in IF won’t take the boolean

Im new here and also I speak spanish, so part of the code is in it.
Well, I have this Java Class that asks for two numbers, and the code adittion, substraction, multiply and divide.
The idea of the exercise is that if one of the numbers is 0, the method of multiply and divide have to return a message that said “Error”, I tried it with a if but the statement in it isn’t working and i don’t know why. I would take any help, thank you very much!

HERE IS THE MAIN PROCESS

public static void main(String[] args) {
    
    Scanner scan = new Scanner(System.in).useDelimiter("n");

    Operacion n1 = new Operacion();
    
    System.out.println("Ingrese el primer número");
    n1.setNumero1(scan.nextInt());
    System.out.println("Ingrese el segundo número");
    n1.setNumero2(scan.nextInt());
    
    int suma = n1.sumar();
    System.out.println("Suma: " + suma);
    n1.restar();
    int res = n1.multiplicar();
    System.out.println("Multiplicación: " + res);
    n1.dividir();
}

HERE THE CLASS

public class Operacion {

private int numero1;
private int numero2;
public int multiplicar() {
        int res;
        if ("0".equals(numero1) || "0".equals(numero2)) {
            res = 0;
            System.out.println("Error");
        } else {
            res = (numero1 * numero2);
            
        }
        return res;
    }
    
    public void dividir(){
        if ("0".equals(numero1) || "0".equals(numero2)) {
            System.out.println("Un número es 0");
            System.out.println(0);
        } else {
            System.out.println("División: " + (numero1 / numero2));
        }
    }

}