Math.eval Support: The function may exhibit sporadic behavior, occasionally functioning properly and occasionally

Just dipping my toes into the coding world and currently working on a web app that's like a dashboard. I'm using node js, express, and mongoose.

I've set up my schemas and collecting user data. There's some data I need to crunch numbers with for calculations.

This is what my model looks like:

var mongoose = require("mongoose"),
    math     = require('mathjs');

//*****DATABASE CONFIG*******
// Demog Database
 var headcountSchema = new mongoose.Schema({
    headct_start: Number,
    headct_end: Number,
    m_mgr: Number,
    f_mgr: Number,
    m_stf: Number,
    f_stf: Number,
    m_ops: Number,
    f_ops: Number,
    m_mru: Number,
    f_mru: Number,
    m_intl: Number,
    etc....
    created: {type: Date, default: Date.now},
    user: {
      id: {
       type: mongoose.Schema.Types.ObjectId,
       ref: "User"
      },
     username: String
    }
    });
module.exports = mongoose.model("Headcount", headcountSchema);

When it comes to performing calculations, I'm following this format:

headcountSchema.virtual('totalmanager').get(function() {  
    return math.eval(this.m_mgr + this.f_mgr);
});

It's puzzling why it works for some fields but not others despite being in the same format.

For instance, it calculates correctly for 'totalmanager' but fails for these:

headcountSchema.virtual('totalintl').get(function() {  
    return math.eval(this.m_intl + this.f_intl);
});

headcountSchema.virtual('totalmru').get(function() {  
    return math.eval(this.m_mru + this.f_mru);
});

When I try to display these values in my ejs file, nothing shows up:

<div class="four wide column grid ui statistic">
  <div class="value">
    <%=headcounts.totalmru%>
  </div>
  <div class="label">
    Employees in Mru
  </div>

Also, how do I handle divisions? When I add "" or (), the values become invalid and no calculation occurs. (Additionally, if I divide by a number, the number turns red)

Answer №1

When the types of variables like m_mgr, f_mgr, m_mru, f_mru are clearly defined as numbers, there is no need to use math.eval(). Instead, you can simply return an expression.

headcountSchema.virtual('totalmanager').get(function() {  
    return this.m_mgr + this.f_mgr;
});

headcountSchema.virtual('totalintl').get(function() {  
    return this.m_intl + this.f_intl;
});

headcountSchema.virtual('totalmru').get(function() {  
    return this.m_mru + this.f_mru;
});

The purpose of the math.eval() function is to evaluate JavaScript code provided as a string. The input parameters must be in string format.

If your input is an expression like math.eval(2 + 2), it will yield the same result as math.eval(4) = 4 since the expression is executed and then evaluated. Therefore, using 2 + 2 directly without math.eval() would suffice (unless dealing with characters and strings).

It's important to pay attention to the data types of the values being passed.

 math.eval('2 + 2') = 4 
 math.eval('2' + '2') = 22
 math.eval('2' + '+' + '2')= 4
 math.eval('2' + 2))= 22

Hence, my suggestion would be to avoid using math.eval() in this context unless I have misunderstood the issue. Feel free to correct me if that's the case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while building with npm on a particular device: spawn EACCES

When executing npm run dev with identical source code and configuration on two separate machines, one of them generates the following error: > node build/dev-server.js internal/child_process.js:302 throw errnoException(err, 'spawn'); ...

The connections within MongoDB between documents across various collections

I'm still weighing my options on this issue, which is why I revisited the problem and made some edits to the original question below. For a weekend project using mongoDB, I need to establish some relationships in the database, which has been quite ch ...

Leveraging Variables within my .env Configuration

Does anyone have suggestions on how to set variables in my environment files? Website_Base_URL=https://${websiteId}.dev.net/api In the code, I have: websiteId = 55; and I would like to use config.get('Website_Base_URL'); to retrieve the compl ...

Is it necessary to keep using npm-shrinkwrap.json for the project to function properly? Are there any drawbacks to maintaining this approach?

After days and days of my application not building, it took me around 12 hours to finally get it working again using npm shrinkwrap I'm wondering if there are any notable drawbacks to this approach. I'm also considering trying out yarn in case i ...

When using a RESTful API that stores images in the filesystem, how will the client access the image when sending a GET request?

After creating a RESTful API using Node/Express, I have managed to allow clients to upload photos and audio files which are stored in the filesystem using multer. However, I have not yet figured out how to store these files in the database. The question ...

Encountering an issue with the command "npm run build" throwing an error during execution

Encountering an error while executing npm run build: Looking for assistance to resolve this issue. Contents of Package.json file: { "name": "confusion", "version": "1.0.0", "description": "This ...

"Exploring the process of saving a Mongoose object using the request body

Attempting to save an object to the database using mongoose express: const data = req.body const product = await Product.create({ ...data }); An error is displayed: TypeError: Cannot read property 'title' of undefined Even though the title ...

Having trouble with the installation of Cypress using NPM? Receive the error message "spawn C:Program ENOENT"?

Struggling with this error for an entire day, unable to find a solution online. I have two laptops side by side - one where Node.js and Cypress are installed without issues, and the other throwing errors. I've tried everything from reinstalling, chang ...

Empty endpoint authorization for Azure Bot

Background : Currently, I am engaged in a project involving a bot on Azure. I have set up a "bot channel registration" to establish an endpoint for receiving messages from Skype for Business. This endpoint is hosted on our server, and while we are able to ...

As I work on developing a React app, I keep encountering this specific error

C:\Users\souvik das>cd documents C:\Users\souvik das\Documents>npx create-react-app blog Creating a new React app in C:\Users\souvik das\Documents\blog. Installing packages. This may take some time. Ins ...

How can I upload a file with MeteorJS?

(Originally posted on the Meteor forums) Imagine wanting to transfer a file from one computer to a server powered by Meteor through HTTP when the second computer triggers a specific API. I successfully built an application for this purpose using NodeJS, ...

Next.js - Reconstructing exclusively fresh sections

I'm currently working on developing a website that will only update two pages and create one new page daily. To achieve this, I need to utilize an API route in a NodeJs backend for creating the new page and updating content through an API to update th ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

Issue: Unable to locate the 'stream/web' module while attempting to execute 'npm start' for a Next.js application, even though the Node version is correct

When I attempted to set up a new application using npm create next-app --typescript, everything seemed to be going smoothly. However, upon trying to start the project with npm start, an error message popped up stating "Error: Cannot find module 'strea ...

Converting a 'Functional Component' to a 'Class Component' in React with Material-UI: A Step-by-Step Guide

Can anyone help me convert this Material-UI example into a Class Component? import React from 'react'; import Button from '@material-ui/core/Button'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@mate ...

Displaying the data from a database on a browser using node.js, MySQL, and Jade

Currently, I am delving into Node.js, Express.js, and Jade while utilizing a MySQL database. As a newcomer to node.js, I decided to start with something simple: presenting data from the database in a table on the browser. Unfortunately, my attempts have no ...

"Failed to insert or update a child record in the database due to a SQL

I encountered an issue while trying to perform the following transaction: static async save(habit){ await db.beginTransaction; try { await db.execute('SELECT @habitId:=MAX(habits.habitId)+1 FROM habits'); await db.execute( ...

What could be causing the 404 error message in Backend deployment on Vercel?

Hello everyone, I'm currently in the process of deploying the backend for my MERN application on Vercel. Prior to this attempt, I successfully deployed a small todo project using MERN on Vercel. Everything worked fine then, and I followed the same st ...

Best practices for writing tests in express.js

After following online tutorials, I discovered that tests can be written using mocha. I successfully wrote a small one that I found online. var assert = require('assert'); describe('Array', function() { describe('#indexOf()&apos ...

Splitting data in NodeJS sockets

Whenever I encounter the need to divide data, my standard practice involves converting it into a string format. Here's an example of how I handle data in my function: socket.on('data', function (data) { var str = data.toString().spl ...