The data input into Express and Mongoose is failing to save

I am having trouble saving a new object, as one of the fields is not being saved even though all others are saved successfully.

In my Mongoose schema, I have defined a property called superPlotId:

const mongoose = require('mongoose');
const GeoJSON = require('mongoose-geojson-schema');
const Schema = mongoose.Schema;
const plotSchema = new Schema(
    {
        ...fields...
        superPlotId: String,
        ...more fields
    },
    { strict: false },
    { bufferCommands: false }
);

//create model class
const ModelClass = mongoose.model('plot', plotSchema);

//export model
module.exports = ModelClass;

When trying to save a new object that adheres to this schema using Express, I do it like this:

exports.newPlot = async (req, res, next) => {
    const {
        ...a bunch of fields...
        superPlotId
    } = req.body.props;
    const plot = new Plot({
        ...a bunch of fields...
        superPlotId
    });
    console.log(('new plot:', JSON.stringify(plot)));
    try {
        const newPlot = await plot.save();
        res.json(newPlot);
    } catch (e) {
        console.log("couldn't save new plot", JSON.stringify(e));
        return res.status(422).send({ error: { message: e, resend: true } });
    }
};

Despite confirming that a correctly formatted object is reaching the endpoint through the console.log above:

{...bunch of fields..."superPlotId":"5a9e9f9f0f8a8026005fe1e7"}

The plot in the database does not include the superPlotId field.

If anyone has insight into what might be causing this issue, please let me know!

Answer №1

Give this a shot!

try {
    let diagram = new Diagram();
    diagram = Object.assign(diagram, req.body.data);
    const updatedDiagram = await diagram.save();
    res.json(updatedDiagram);
} catch (error) {
    console.log("Failed to save updated diagram", JSON.stringify(error));
    return res.status(422).send({
        error: {
            message: error,
            retry: true
        }
    });
}

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

Encountering issues when setting fitbounds beyond the scope of a jquery.each()

I am currently working on a Google Map project using JavaScript(v3). My goal is to display markers from XML data by utilizing jQuery. Below are the object and function that I have created to streamline this process: var VX = { map:null, bounds ...

Is it possible to retrieve browser history from Google Chrome using Node.js on a Windows operating system?

I'm currently developing a personal electron app for managing my lifestyle. One of the key features is controlling my daily internet browsing through the app. I am aiming to integrate my Chrome history into the electron app. Could someone recommend a ...

The TypeORM connection named "default" could not be located during the creation of the connection in a Jest globalSetup environment

I've encountered a similar issue as the one discussed in #5164 and also in this thread. Here is a sample of working test code: // AccountResolver.test.ts describe('Account entity', () => { it('add account', async () => { ...

Implementing a custom stylesheet in the Express static directory

I recently configured the static folder in this way: app.use(express.static(path.join(__dirname, '/public'))); In my HTML code, I linked to a style sheet located in "public/stylesheets" like so: <link rel="stylesheet" href="stylesheets/styl ...

Is it possible for a JavaScript environment to restore function normally after modifying the [[Prototype]] of an object?

After thoroughly reviewing the MDN disclaimers and warnings, as well as an enlightening discussion in a popular online forum, I still find myself seeking answers. This question arose from a previous exchange, which can be found here. Imagine if I were to ...

I am encountering an issue where the useState hook is returning an undefined value on separate components, even after

When setting up a login context, I wrap all my routes with the context provider and pass the initial value using useState: <userContext.Provider value={{loggedUser, setLoggedUser}}> In LogInMenu.jsx, which is responsible for setting the loggedUser ( ...

Using Javascript to create a conditional variable within a function

Attempting to conditionally set a variable to handle the first click user case. The goal is to set the variable based on that condition. An attempt is made to instantiate a model which retrieves the variable, but on the first click, the model has not been ...

Exploring content within a nested directory on AWS S3

I'm currently experimenting with an ajax request in order to retrieve all image files from a specific subfolder within my S3 bucket. Even though I have set the subfolder to public access using the dropdown menu (view image for reference), I keep enco ...

The conversion of a 2D json array into a string is mistakenly performed

On hand is an outer array that contains 2 arrays within it, making it a 2-dimensional array. This is how the array is initialized: $outerArray = array(); $nestedArray = array("first", "second", "third", "fourth"); $outerArray[] = $nestedArray; $nest ...

Click the button to save the text to your clipboard with a customized

Can anyone suggest a method for duplicating div text using JavaScript while preserving the style attributes (italics, font family, size, etc.)? My goal is to paste the copied text into Word and have it maintain the same appearance as on the webpage. For e ...

How can you retrieve script data within HTML and PHP tags?

I am currently working on a web application using CodeIgniter-3 and I have encountered an issue with a form that contains two dropdowns which are dependent on each other. When a selection is made in the first dropdown, the data in the second dropdown sho ...

jQuery does not support animations for sliding up or down

I'm struggling to conceal a navigation element once the top of the #preFooter section is scrolled to. In order to make the nav element mobile-friendly, I have designed both the .tab-wrap and .tab-wrap-mobile. To enable these elements to slide away w ...

Having to click twice in order to close the jQuery dialog box can be frustrating

I've been attempting to set up a div that pops up using jQuery dialog. Initially, when the user clicks on the button and opens the dialog, it closes with the first click. The second time they try to close the dialog, it will reopen the same popup, r ...

Storing form data in a JSON file using JavaScript

For a while now, I've been pondering over this issue. My plan involves creating a desktop application with Electron. As a result, I am working on an app using Node.js and Express.js. The project includes a simple app.js file that executes my website&a ...

Is there internal access to the "access property" within the "data property" in JavaScript?

I have come to understand that there are two types of properties in objects: data properties and accessor properties. It is possible to access the "data property" without using an "accessor property," as shown below: const person = { name: 'Pecan&a ...

Using only THREE.Points, it is possible to dynamically calculate the camera position in three.js

My primary objective is to dynamically position the camera in such a way that my object remains visible. After researching, I came across this thread: How to Fit Camera to Object This article mentions the need for fov, height, and dist, variables which a ...

Filtering in AngularJS can be done by combining two fields at

I attempted to implement similar code for filtering my tasks, but it seems to be malfunctioning. When I use just one filter, everything works fine regardless of which one I choose. However, when I attempt to filter by the second input, it simply does not w ...

What could be causing the closest() method in my JavaScript code to not locate the nearest class?

I've encountered an issue while dynamically creating new classes with input fields in my project. For some reason, when I try to remove a previous row, nothing happens. Can anyone help me troubleshoot this problem? Here is the JavaScript code that I ...

Whenever I navigate to a new page in my NEXTJS project, it loads an excessive number of modules

I am currently working on a small Next.js project and facing an issue where the initial load time is excessively long. Whenever I click on a link to navigate to a page like home/product/[slug], it takes around 12 seconds to load due to compiling over 2000 ...

The current issue lies in the NodeJS axios API call that is attempting to access data from an AWS S3 bucket, but it is not functioning correctly. Please note that

Essentially, I am utilizing two API services known as service1 and service2. For service1, which is constructed using expressJS, the code looks like this: const fetchDocument = catchAsync(async (req, res) => { const data = await getDocument(); if ...