Issues with MEAN stack post method not updating database records

I'm having trouble passing data via HTTP post method and seeing the changes reflected in the database. This is the code snippet:

addJobList(jobitem) {
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    var selected = {
      companyTitle : jobitem.company,
      jobTitle : jobitem.jobtitle,
      location : jobitem.location
    }
    console.log(selected);
    this.http.post('http://localhost:3000/api/appliedjobs', JSON.stringify(selected),{headers: headers})
    .map(res => res.json());
  }
//fetching jobs from backend
  getAppliedjobList() {
    if (this.jobslist) {
      return Promise.resolve(this.jobslist);
    }
    return new Promise( resolve => {
      let headers = new Headers();
      headers.append('Content-Type','application/json');
      this.http.get('http://localhost:3000/api/appliedjobs',{headers: headers})
      .map(res => res.json())
      .subscribe(data => {
        this.jobslist = data;
        resolve(this.jobslist);
      });
    });
  } 

The object 'selected' contains the data.

{companyTitle: "Facebook", jobTitle: "System Engineer", location: "Toronto, Canada"}

I can see the data in the console. However, it does not seem to be inserted into the database. Here is the code from my routes folder:

const jobList = require('../models/jobList');
router.post('/appliedjobs', function(req,res) {
  console.log('posting');
  jobList.create({
    companyTitle: req.body.companyTitle,
    jobTitle: req.body.jobTitle,
    location: req.body.location
  },function(err,list) {
    if (err) {
      console.log('error getting list '+ err);
    } else {
      res.json(list);
    }
  }
  );
});

No errors are being reported, but the data is still not being added to the database. Here's an overview of my model:

var mongoose = require('mongoose');

const joblistSchema = mongoose.Schema({
    companyTitle: String,
    jobTitle: String,
    location: String,
});

const JlSchema = module.exports = mongoose.model('JlSchema',joblistSchema,'joblist');

Answer №1

In order to send your data, you do not have to encode it as shown in the following link. Make sure to return the this.http.post method.

submitJob(jobDetails) {
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    const jobInfo = {
      companyTitle : jobDetails.company,
      jobTitle : jobDetails.jobTitle,
      location : jobDetails.location
    }
    return this.http.post('http://localhost:3000/api/jobs', jobInfo, { headers: headers })
    .map(response => response.json());
  }

To make use of it, remember to subscribe to your submitJob function. http.post acts as an observable and requires subscription for making the call:

submitJob(theJobDetails).subscribe(result => console.log(result));

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

Angular version 6: The 'fromEvent' property is not found on the 'Observable' type

I am working on developing a custom sticky navbar directive for the sticky header in my angular 6 application. This is what I have accomplished so far: import { Directive, Input, Renderer, ElementRef, OnInit } from '@angular/core'; import { Obs ...

Tips for refreshing an element after modifying a data-* attribute

I have an element that has the following CSS style: #element:after { content: attr(data-percent); } In an attempt to change the data-percent attribute using jQuery, I used this code: $('#element').data('percent', '50%'); ...

What is the process for injecting dependencies in a custom Angular class?

I am facing an issue with my Angular service setup: @Injectable({ providedIn: 'root', }) export class Services { public service1 = new Service1(); } The Service1 class looks like this: export class Service1 { public http: HttpRequ ...

Is there an equivalent to Tomcat specifically designed for Node.js applications?

Looking for an application server that offers an administration interface to deploy node.js applications, access log files, and manage running applications with options to start, stop, restart, and monitor? ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: https://i.sstatic.net/jaLmg.png Is there a way to hide them from being easily accessib ...

Is it possible to group an array of objects by a specific element?

Take a look at this example: JsFiddle Query: I'm dealing with the following JSON Array y= [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000}, {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000}, {"LngTrend":17,"DblValue":45,"DtmSta ...

Extracting content from a page that requires JavaScript to be rendered

I need to extract data from a dynamically rendered JavaScript page using Selenium web driver in Python3. I've tried various drivers like Firefox, Chromedriver, and PhantomJS, but I always end up with the script rather than the DOM element. Below is a ...

"Optimize your website by incorporating lazy loading for images with IntersectionObserver for enhanced performance

How can I use the Intersection Observer to load an H2 tag only when the image is visible on the page? Here is the JavaScript code I currently have: const images = document.querySelectorAll('img[data-src]'); const observer = new IntersectionObser ...

Use JavaScript regex to replace a string only if its length exceeds a certain specified limit

My current approach involves using JavaScript regex to insert an HTML markup for all identified URLs: var exp = /(((|www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|&bso ...

AngularJS enthusiasts have the ability to curate a personalized list of favorites

I am looking to implement a feature in my application where users can create a favorite list based on their selection. The application utilizes a lengthy JSON file containing a multitude of text, which is loaded using $http.get(). Below is the code segment ...

Is there a way to verify file types using Vuelidate?

Is there a way to validate file types like png, jpg, and jpeg using Vue.js's Vuelidate library? ...

The 'type' property is not defined in the current type, however, it is expected in the 'Props' type

https://i.sstatic.net/7bD1N.pngI encountered an unusual typescript error in my IDE on line 16 when I was converting my React ES6 component to TypeScript. The error pertains to a chart component that utilizes react-chartjs-2. The error message states that ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

What method can be used to fetch generic type parameter in typescript?

I am having trouble finding the type of E within the code provided below. class A<E> { getParameterType() { // I need to determine the type of E } } class B { } ** Example ** new A<number>().getParameterType() // number new A<B&g ...

VueJS avoids displaying a specific data in every iteration of a v-for loop

Presented below is the code that I have managed to successfully get working: <span v-for="(item, index) in storedUserItems"> <template v-if="item.strength"> <img @mouseover="itemInfo(item, index)" style="padding: 5px;b ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

Is there a way to turn off the pinch-to-zoom trackpad gesture or disable the Ctrl+wheel zoom function on a webpage

Take a look at this example - While zooming in on the image by pressing ctrl + scroll, the image zooms but the page itself does not scale. Only the image is affected by the zoom. I am attempting to replicate this functionality on my Next.js page. I have ...

What is the best way to dynamically incorporate Before After CSS code in Vue?

I am facing a unique challenge in my current project. I need to dynamically apply colors from data inside a v-for loop, specifically for the :after CSS pseudo-element. While normal CSS properties are easily applicable, I am struggling with applying styles ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

Error: The argument provided for user.token is of type 'string | undefined' which cannot be assigned to a parameter of type 'string'

I'm currently engaged in a project that involves ASP.NET Core Web API and Angular 13. Here is the login post request from the endpoint: > https://localhost:44396/api/v1/auth/login { "status_code": 200, "message&qu ...