How to Send TypeScript Object Excluding the '_id' Field?

I am currently developing a web app using Express, Mongoose, and Angular 2 (TypeScript). I want to post an instance of MyClass without including the _id field.

In mongoose, the _id field is used for various operations in MongoDB. Here is how I have implemented it on the server side using mongoose:

router.post('/', function(req, res, next) {
  Package.create(req.body, function (err, post) {
    if (err) return next(err);
        res.json(post);
  });
});

/* GET /package/id */
router.get('/:id', function(req, res, next) {
  Package.findById(req.params.id, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

/* PUT /package/:id */
router.put('/:id', function(req, res, next) {
  Package.findByIdAndUpdate(req.params.id, req.body, function (err, post, after) {
    if (err) return next(err);
    res.json(post);
  });
});

To exclude the _id field, I have created a TypeScript Class like this:

export class Package{
    constructor(
        public guid: string,
        ...
        [other fields]
        ...
        public _id: string
    ){}
}

Please note that the _id field is included at the end.

In my Angular 2 service, I am posting the JSON object to the server using the following method:

//create new package
private post(pck: Package): Promise<Package> {
    let headers = new Headers({
        'Content-Type': 'application/json'
    });

    return this.http
        .post(this.packageUrl, JSON.stringify(pck), { headers: headers })
        .toPromise()
        .then(res => res.json())
        .catch(this.handleError);

}

However, I encountered an error as shown in the screenshot below:

https://i.sstatic.net/r6Mp3.png

The error indicated that the object I posted back had an empty _id field.

How can I post a ts class without including the _id field, or should I approach this problem differently?

Answer №1

After realizing no one had provided an answer, I took to the internet and discovered a fantastic example of how to set up an Angular2 -- Mongoose -- Express System.

https://github.com/moizKachwala/Angular2-express-mongoose-gulp-node-typescript

This is a well-documented example featuring the original Hero App from the official tutorial. While it may be based on RC1, it serves as a solid starting point for properly handling RESTFUL Requests.

I trust that this will assist anyone in search of a similar solution.

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

A guide on simulating childprocess.exec in TypeScript

export function executeCommandPromise(file: string, command: string) { return new Promise((resolve, reject) => { exec(command, { cwd: `${file}` }, (error: ExecException | null, stdout: string, stderr: string) => { if (error) { con ...

Postman is displaying an UnhandledPromiseRejectionWarning error stating that the "username" parameter has an invalid value of "undefined."

Currently, I am in the process of developing a backend using nodejs for a login page. I came across this helpful tutorial on JWT authentication with MySQL: However, when attempting to access http://localhost:8080/api/auth/signup in Postman, I encountered ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: https ...

Which Index Type is the best fit for my assignment?

Color, by default, is a string that is set to primary. However, when used as an index in the Colors array, I encounter an issue where it is recognized as an any type. This happens because a string cannot be used as an index on type '{..etc}' The ...

Sorry, access is not available due to CORS policy restrictions, even after 'Access-Control-Allow-Origin' has been set

My issue lies in the CORS configuration on render.com, where I am hosting both the client and server. Despite setting up cors to allow the origin that's being blocked, I keep encountering this error. The error message is: video-streaming-client.onren ...

Having issues with referencing external JavaScript and CSS files in Angular 6

Dealing with an angular6 project and a bootstrap admin dashboard template, I'm facing issues importing the external js references into my Angular application. Looking for guidance on how to properly import and refer to external Js/CSS files in an angu ...

Transitioning a JavaScriptIonicAngular 1 application to TypescriptIonic 2Angular 2 application

I am currently in the process of transitioning an App from JavaScript\Ionic\Angular1 to Typescript\Ionic2\Angular2 one file at a time. I have extensively researched various guides on migrating between these technologies, completed the A ...

Creating a Typescript interface for a anonymous function being passed into a React component

I have been exploring the use of Typescript in conjunction with React functional components, particularly when utilizing a Bootstrap modal component. I encountered some confusion regarding how to properly define the Typescript interface for the component w ...

Searching for documents that do not contain a certain value within an array field in Mongoose

When working with Mongoose, imagine a scenario where model M includes the following field: list: {type:[String]} What is the best approach to locate a document in which a specific value x is not part of the 'list'? Is there perhaps a unique ope ...

Is there a suitable alternative that supports TypeScript, particularly with Angular 6, as D3Js does not directly support TypeScript?

I am currently engaged in a new project focusing on HR Analytics, utilizing Python, R, MySQL, and Angular 6 for the front end user interface. In terms of Data Visualization, I am exploring the use of D3js. However, it is important to note that D3Js does no ...

What is the best way to modify a schema array in MongoDB with mongoose?

Is it possible to query an item from MongoDB, make changes like with any other object, and then use the save method to update it in the database? It seems that this approach doesn't work seamlessly for my schema array. I don't have much experienc ...

Angular 6 and Typescript: How to Map Objects in Arrays within Arrays

We currently have two arrays named speisekarte (consisting of 10 objects) and essensplan (containing 8 objects). const speisekarte = [ { id: 11, name: 'Kabeljaufilet', price: 3.55, type: 'with fish' }, { id: 12, name: 'Spaghet ...

Error in NodeJS (EJS): Unable to locate stylesheet file

Having trouble adding a CSS file to my Node.js project with the EJS Template Engine. The file cannot be found when trying to access it. GET http://localhost/css/bulma.css net::ERR_ABORTED 404 (Not Found) Project folder structure ./index.js ./views ...

Can you provide instructions on using Sequelize to update the quantity of items in a cart database if they already exist, or create them if they do not exist?

As a novice programmer delving into the world of e-commerce website development, I find myself grappling with the task of implementing the cart feature. My tech stack of choice is the NERP stack - Node, Express, React-Redux, and Postgres. Specifically, m ...

Removing a column in an Angular application using the xlsx library

I'm trying to figure out how to remove the last column from a table when using the xlsx library. I'm working on saving data from my Angular application, but there is one column called "description" which just contains icons and I don't want ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

LocalStorage in Angular application failing to function in Android web view

Working with Angular 4, I've developed a web application that stores the user security token in localStorage after login. The application uses this localStorage value to control the visibility of certain links, such as hiding the login button once th ...

Importing styles from an external URL using Angular-cli

How can I load CSS styles from an external URL? For instance, my domain is domain.eu but my site is located at sub.domain.eu. I want to use styles that are stored on the main domain (common for all sites). The example below does not work: "styles&qu ...

s3 is having trouble uploading the file and is returning an error stating SignatureDoesNotMatch

I'm experiencing an issue while attempting to upload images to my s3 bucket in aws. The error message SignatureDoesNotMatch keeps appearing. Below is the code I am using to upload the file/image: FrontEnd const file = e.target.files[0]; const fileP ...