JavaScript failing to link an element to the object

const modifyTimestamp = async (request, response) => {
  try {
    const { user: userid } = request;
    if (!ObjectId.isValid(userid)) throw new Error('invalid objectid');

    const now = moment().format();
    const date = new Date(now);
    const result = await Allocation.findOne({ $and: [{ user: userid, start_date: { $lt: date }, end_date: { $gt: date } }] })
      .populate('user', 'name')
      .populate('garden');
    if (!result) throw new Error('invalid request');
    result.timestamp = moment(result.end_date).format('x');
    response.status(200).send(result);
  } catch (error) {
    response.status(400).send(error);
  }
};

I've encountered an issue where the timestamp is not added to the returned object from the MongoDB query. Even when trying to log the timestamp value, it doesn't appear. It seems like JavaScript is disregarding my assignment. I experimented with changing from const to let but that didn't solve the problem.

Answer №1

..it seems like javascript is not recognizing my attempt to assign it.

It's a possibility that JavaScript is disregarding the assignment if the object is either sealed or frozen by MongoDB.

Instead, create a duplicate and append your property to the duplicate using ES2018's property spread:

allocation = {...allocation, timestamp: moment(allocation.end_date).format('x')};

...or if you cannot utilize property spread, use Object.assign:

allocation = Object.assign({}, allocation, {timestamp: moment(allocation.end_date).format('x')});

You will need to switch from const to let in these situations since we are altering the value stored in the variable allocation. Alternatively, you can keep it as a const and retain the modified version separately:

const updatedAllocation = {...allocation, timestamp: moment(allocation.end_date).format('x')};
response.status(200).send(updatedAllocation);

I attempted changing from const to let but it appears that's not the root of the problem.

That's correct. const pertains to the variable (allocation), not the object the variable points to.

Answer №2

The documents retrieved from the query consist of mongoose/mongodb objects, not basic javascript objects.

To make any changes to the document, you need to either assign it to new Object(), or utilize the .lean() option which converts the mongoose object to a regular javascript object.

const record = await Record.findOne({})
      .populate('user', 'name')
      .populate('garden')
      .lean()
if (!record) throw new Error('invalid request');
record.timestamp = moment(record.end_date).format('x');

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

Next.js is refusing to render an array of HTML elements

Consider this scenario where I have a block of code in TypeScript that attempts to create and display a list of elements. Here is a sample implementation: const MenuList = ():ReactElement => { const router = useRouter(), liElements:any = []; con ...

Order comments based on their category using vue.js

I have a component form with select filter: <template> <div class="form-group"> <select name="" v-model="filterRev" @change="filterReviews(filterRev)" class="form-control" id=""> <option ...

The modal window does not display a scroll bar

I'm currently facing an issue where the scroll bar is not appearing on my page when more elements are added. In addition, I have a modal that covers the entire page when clicking on an item. However, changing the CSS position: fixed property affects ...

Axios sending a 400 Bad Request to Django due to a missing required field

I'm having issues sending a POST request from my React frontend using Axios. import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { ...

Is Firefox preventing the running of asynchronous JavaScript code?

My experience with writing tests for my web application in the Selenium Framework has been smooth sailing with both Chrome and Edge. However, I've encountered a problem specifically with Firefox - the asynchronous script keeps timing out. I suspect i ...

When the dialog is opened, automatically set the focus on the text field inside

I am facing an issue with focusing a custom text field when opening a dialog. I have tried using vue.js refs: Code: <v-app id="app"> <v-row align="center"> <v-col class="text-center" cols="12"> <v-btn color="primary" @cli ...

Tips for ensuring a custom menu closes when clicking outside of it instead of on the menu itself

Building off a recent inquiry, I am aiming to have my menu close whenever I click outside of it. At the moment, clicking the "Hamburger Menu Button" opens and closes the menu. It will also close when I click a link on the menu or the menu itself. However, ...

Whispering form using onblur and onfocus

Seeking assistance with echoing a form that includes multiple input fields. Specifically, I am attempting to utilize onblur and onfocus (refer to the conditions outlined in the code). However, I am encountering an issue where the Javascript function does ...

Having trouble selecting a radio button in React JS because it's marked as read-only due to the check attribute

In my scenario, I have a child component with radio buttons. The questions and radio buttons are populated based on the data, with each set consisting of one "yes" and one "no" option. I am attempting to automatically check all radio buttons that have a v ...

Guide to attaching and displaying an image on a Three.js map

Currently, I have a 3D map loaded with three.js that includes mouse interaction. I've managed to place an image on the map using absolute positioning, but unfortunately, as I move the map around, the image stays stationary. Does anyone know how I can ...

Efficient File Upload Feature Compatible with all Browsers, Including Internet Explorer versions 7, 8, and 9

Can someone assist me with a problem I'm facing? I need a code script that enables multiple file uploading on all browsers. While HTML5 supports Chrome and Mozilla Firefox, it does not support IE. I am looking for a script/jquery solution that works ...

Adding a duplicate field with a unique value in MongoDB

Can anyone suggest a script that can update a document by adding a duplicate field with a new value? Utilizing "set" is not an option as it overrides the current value. Similarly, "push" cannot be used because the field is located in an object, not an ar ...

An improved method for fetching data from the server at regular intervals of x minutes

Is setInterval the best way to periodically check for updates in a database and update the UI accordingly, or are there better approaches that I should consider? I've read conflicting opinions on using setInterval for this purpose, with some sources ...

An error occurred as the requested resource does not have the necessary 'Access-Control-Allow-Origin' header. The response code received was 403

I am working with Angular products services that make calls to the "http://jsonplaceholder.typicode.com/posts" URL using the HttpClient method. However, I am encountering the error message "No 'Access-Control-Allow-Origin' header is present on t ...

Is there a way to keep this function running endlessly when hovering?

Is there a way to modify this function so that the classes of my links continuously change colors while I hover over them, rather than changing only once? <script type="text/javascript"> $(".nav a").hover(function(e){ var randomC ...

Guide to presenting a personalized date format in an Angular table by utilizing the gantt-tooltip attribute

How can I customize the date format displayed in the tooltip to only show the month and day (e.g. Sep 01) within an Angular Gantt table? Currently, the date is being shown in the default format "MMM DD, HH:mm". Can anyone assist me in resolving this issue ...

I would like for this message to appear periodically following the initial execution

I have developed a unique welcome feature using HTML and CSS that I would like to showcase intermittently. --------------------------- My Desired Outcome --------------------------- Initially, this feature should be triggered once (when a user first acce ...

In React and Node Js, the setState function will return a value of NULL

My Node Js API utilizes a find function to retrieve data from the database, which works flawlessly and returns the results. However, when I pass this data into setState using React and Axios, it ends up returning null. Below is my API's find() functi ...

Upon redirecting to a new page following the loading of a previous page

At the moment, I have a webpage where filling out a text box and clicking a button redirects you to another page. This page must be loaded because it updates and displays XML data (this aspect cannot be changed). However, my goal is to either redirect th ...

Fade In/Out Scroll Effect

As the user scrolls down the page, I have a slider that smoothly slides from right to left. What I'm trying to achieve is for the slider to fade out when the last slide is no longer in view during downward scrolling, and fade back in as the last slid ...