Removing based on field data [Interpretation]

I am currently learning about the MEAN stack and I am working on implementing CRUD operations using mongoose. I came across a question on stackoverflow discussing how to delete a document by a specific value in MongoDB, which in my case is an article with a unique articleid. However, I seem to be making some mistakes with params that I am unaware of. Can someone please help me correct them?

Here is a sample document in mongodb:

{
  _id: objectId("5d77de7ff5ae9e27bd787bd6"),
  articleid:"art5678",
  title:"Installing JDK 8 in Ubuntu 18.04 and later",
  content:"<h2>Step 1: Add repository</h2><p><strong>$ sudo add-apt-repository pp..."
  date:"Tue, 10 Sep 2019 17:33:51 GMT"
  contributor:"Tanzeel Mirza",
  __v:0
}

article.component.html

<div class="row mt-5">
    <div class="col-md-4 mb-3" *ngFor="let article of articles;">
      <div class="card text-center">
        <div class="card-body">
          <h5 class="card-title">{{article.title}}</h5>
          <a (click)="onPress(article.articleid)" class="btn btn-danger">Delete</a>
        </div>
      </div>
    </div>
  </div>

The method

(click)="onPress(article.articleid")
triggers a function in the ts file.

article.component.ts

import { Component, OnInit } from '@angular/core';
import { ArticleService } from '../article.service';


@Component({
  selector: 'app-articles',
  templateUrl: './articles.component.html',
  styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {

  articles = []

  constructor(private _articleService: ArticleService) { }

  ngOnInit() {
    this._articleService.getEvents()
    .subscribe(
      res => this.articles = res,
      err => console.log(err)
    )
  }

  onPress(id) {
    this._articleService.deleteArticle()
    .subscribe (
      data => {
        console.log("hello");
      }
    );
  }
}

I have also created a service called article.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ArticleService {
  private _deleteUrl = "http://localhost:3000/api/delete/:id";
  constructor(private http: HttpClient) { }    
  getAllArticles() {
    ...
  }

  deleteArticle(id) {
    return this.http.delete<any>(this._deleteUrl);
  }
}

Lastly, here is my API script api.js:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Article = require('../models/article');
const dbstring = ...


mongoose.connect(dbstring, { useNewUrlParser: true }, err => {
  ...
})

router.delete('/delete/:id', (req, res) => {
  let articleData=req.params.id;

  console.log(articleData); //Output: {}
  console.log('on delete url '+articleData); //Output: on delete url undefined

  Article.deleteOne({articleid: articleData}, (error, article) => {
    if(error) {
      console.log(error)
    }
    else {
      if(!article) {
        res.status(401).send('Something went wrong')
      }
      else {
        //res.json(article);
      }
    }
  })
})

module.exports = router;

If you can't write the code for me, could you guide me towards some helpful study materials at least?

Answer №1

After conducting extensive research, I have successfully identified and resolved the issue at hand. Below are the necessary changes that have been implemented.

api.js

router.delete('/delete/:id', (req, res) => {
  let articleId=req.params.id;
  Article.deleteOne({articleid: articleId}, (error, article) => {
    if(error) {
      console.log(error)
    }
    else {
      if(!article) {
        ...
      }
      else {
        ...            
      }
    }
  })
})

Furthermore, in article.service.ts

private _deleteUrl = "http://localhost:3000/api/delete";

The deleteArticle method has been updated to:

deleteArticle(id) {
    return this.http.delete<any>(this._deleteUrl+'/'+id);
}

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

Leverage TypeScript generics to link props with state in a React class-based component

Can the state type be determined based on the prop type that is passed in? type BarProps = { availableOptions: any[] } type BarState = { selectedOption: any } export default class Bar extends React.Component<BarProps, BarState> { ...

Disabling the experimental app directory feature in NextJs

I've been working on a real-life project and decided to test out the new App directory feature that comes with Next.js version 13. However, I encountered some issues such as images and fonts not loading properly. Now, I'm looking to opt out of th ...

Creating a setup in TypeScript to enable imports between CommonJS and ES modules (for node-fetch and Express)

I'm facing a challenge in trying to integrate two libraries into a single project: fetch-node, an ES module, and Express, which follows the CommonJS format. The issue arises from needing to import fetch-node using: import fetch from 'node-fetch&a ...

Angular is failing to detect a change in the initial element of an array

In my Angular app, I am working on displaying a list of dates for the current week. Users should be able to view previous weeks by clicking a button, so I am using an Observable to update the array of dates and trying to display the updated array. Althoug ...

Passing a parameter in an AngularJS/TypeScript component

I am currently working on a project that involves the integration of angularjs and typescript. Within this project, I have developed a component specifically designed to handle errors. However, I am facing a challenge in retrieving the parameter sent to t ...

What is the rationale behind permitting interface method implementations to have varying intersection type arguments?

The interface and implementation presented here are quite straightforward: class Transform { X: number = 0 Y: number = 0 } class RenderData { Model: object | null = null } interface System { Update(e: Transform & RenderData): void } class Ren ...

"Unlocking the Power of Pandas Dataframes: A Guide to Parsing MongoDB

I have a piece of code that exports JSON data from a MongoDB query like this: querywith open(r'/Month/Applications_test.json', 'w') as f: for x in dic: json.dump(x, f, default=json_util.default) The output JSON looks like this: ...

A simple trick to compile and run TypeScript files with just one command!

Converting TS to JS is typically done using the tsc command, followed by executing the resulting .js file with node. This process involves two steps but is necessary to run a .ts file successfully. I'm curious, though, if there is a way to streamlin ...

The persistent issue of the Mongo Connection repeatedly shutting down

A snippet from a console log: Attempted to GET data from http://localhost:5000/api/goals/, but encountered an error: connect ECONNREFUSED 127.0.0.1:5000. Here are the request headers: User-Agent: PostmanRuntime/7.29.0 Accept: / Postman-Token: 508773a0-790 ...

Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Ple ...

Verify the rendering process in the ForwardRef's render method

I have implemented the code exactly as provided in the example from https://material-ui.com/components/bottom-navigation/: // code in app.tsx: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Bo ...

Set the column span on a particular column within a dynamic table utilizing the mat-table component

I have a dynamic mat-table where columns are created dynamically. I am looking to implement an expand column feature using [attr.colspan]. This functionality should apply the attribute when a click event is detected on a specific column header. When I ins ...

Guide on transitioning a MongoDB replica set into a standalone server

Let's say I have 4 replicate sets and the configuration looks like this: { "_id": "rs_0", "version": 5, "members" : [ {"_id": 1, "host": "127.0.0.1:27001"}, {"_id": 2, "host": "127.0.0.1:27002"}, {"_id": 3, "host": "127.0.0.1:27003"}, {"_i ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

The PathLocationStrategy function is designed to work exclusively within a local

I am facing a hash problem in my current project. Interestingly, everything works correctly in the test project. I have searched on Google for solutions but couldn't find any satisfactory answers: Angular2 without hash in the url When I add {provide ...

Serialization of objects is not possible in Angular JS post requests

At the moment, I am utilizing an AngularJS Post method to send data to my controller instead of a traditional form submission. The issue I am encountering is that after the post call, the object named sharingInfo in the controller always gets set to null. ...

Accessing object properties on the fly in TypeScript

I'm currently working on a TypeScript game that features an inventory system with various values, like so: export const Inventory = { food: 0, medicine: 0, rifleAmmo: 0, pistolAmmo: 0 } At the moment, I have a function in place to man ...

Ionic 3 is unable to find a provider for CallNumber

Recently, I have been working with Ionic 3 and encountered an issue when trying to call a number using the Call Number plugin. Here are the steps I followed to add the plugin: ionic cordova plugin add call-number npm install --save @ionic-native/call-numb ...

Every time I use the putObject method in the Aerospike Golang client, I encounter a panic with the error message: "reflect: call of reflect

I'm currently working on migrating data from MongoDB to AeroSpike using the MGO client for MongoDB. Below is the code snippet: package main import ( "log" "flag" "fmt" ///"reflect" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ...

Describe the process of defining an Interface object array and effectively utilizing it

I have a sample object array structured like this: tasks: todo = [ { title: string, status: number, description: string, date: Date, priority: number } ] To handle this, I created an Interface as foll ...