按字段值 [平均值] 删除



我正在学习MEAN stack。我想执行CRUD操作,并且正在使用mongoose.我正在关注堆栈溢出的这个问题。我想按特定值删除文档。就我而言,这是一个具有独特articleidarticle,应该删除。不知不觉中,我正在params上犯一些可怕的错误。请纠正我。

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
}

文章.组件.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>

(click)="onPress(article.articleid")调用ts文件中的方法。

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");
}
);
}
}

我创建了一个服务文章.服务.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);
}
}

这是我的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;

好吧,不要为我编写代码,但请至少告诉我一些学习材料。

好的。我做了越来越多的研究,找出了问题所在。以下是更改。

接口.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 {
...            
}
}
})
})

文章.服务.tsprivate _deleteUrl = "http://localhost:3000/api/delete";

deleteArticle方法应该是。

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

相关内容

  • 没有找到相关文章

最新更新