【问题标题】:How to delete an element of an array from Mongodb [Angular]如何从 Mongodb [Angular] 中删除数组的元素
【发布时间】:2020-08-19 00:53:28
【问题描述】:

这个问题没有回答我的问题: Delete an element from an array of an array in MongoDb

我创建了一个非常基本的 MEAN 应用程序。我正在创建(或尝试创建)一种 stackoverflow 机制。我有一篇文章,其中有赞成票和反对票。这是mongodb记录的截图。有很多这样的记录:

您可以看到upvotersdownvoters 的数组。我有一个案例,以前对文章投赞成票的当前登录用户现在想要对同一篇文章投反对票。然后他的名字应该从'upvoters'数组转移到downvoters数组。这包括两个步骤:

  1. upvoters数组中删除当前登录用户
  2. downvoters 数组中添加相同的用户。

步骤号2 我可以。但是第1步我遇到了问题。这是我的代码。关注removeUserFromUpvotersList()方法:

article.component.ts

    export class ArticleComponent implements OnInit {
      articleId : String = '';
      article;      

      currentLoggedInUserId: string;    

      updatedVotes={
        articleid: "",
        upvotes: 0,
        downvotes: 0,
        upvoters: [],
        downvoters: []
      };

      ...

      downvoted() {
        console.log("downvoted");
        this.removeUserFromUpvotersList();
      }

      removeUserFromUpvotersList() {
        this.updatedVotes.upvoters.push(localStorage.getItem('userid'));
        this._articleService.removeUserFromUpvotersList(this.updatedVotes, localStorage.getItem('userid'))
        .subscribe (
          res => {
          },
          err => console.log(err)
        );
      }
    }

article.service.ts

export class ArticleService {
  ...
  private _deleteFromUpvotersListURL = "http://localhost:3000/api/remove-from-upvoters-list";
  ...

  removeUserFromUpvotersList(updatedArticle, id) {
    return this.http.delete<any>(this._deleteFromUpvotersListURL+'/'+id, updatedArticle);
  }
}

api.ts

router.delete('/remove-from-upvoters-list/:id', (req, res) => {
    console.log("removing from upvoters list");
    let userId = req.params.id;
    let articleId = req.body.articleid;
    Article.update({ articleid: articleId }, { $pull: { upvoters: userId } }).then(opResult => console.log(opResult));
    Article.deleteOne({ userId: userId }, (error, userId) => {
        if (error) {
            console.log(error)
        } else {
            if (!article) {
                res.status(401).send('something went wrong')
            } else {
                console.log('successfully deleted');
            }
        }
    })
})

我知道我的 api 工作正常,因为我能够执行添加和更新操作。请帮我删除。

【问题讨论】:

    标签: angular express mean-stack


    【解决方案1】:

    在前端调用 put 方法,后端端点被删除。 在前端服务中更改为 http.delete 应该可以解决问题。

    【讨论】:

    • 很好地抓住了大卫。我把它改成删除。但问题依然存在。
    • 您是否在后端应用程序中记录了一些内容?
    • 是的。用户名和密码。
    • 如果删除成功,您不响应任何内容。你可以使用res.sendStatus(200)
    • 删除本身不成功。这就是我的问题。
    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 2017-12-22
    • 2015-06-12
    • 2013-06-02
    • 2016-02-25
    相关资源
    最近更新 更多