使用mongodb

时间:2018-05-05 13:33:50

标签: angular express mean-stack

对于学校我正在Angular制作一个具有特定目标的项目,我们没有上过很多课程,所以我还是初学者。我的项目差不多完成了,但我偶然发现在MongoDB数据库中更新我的文档。 我的项目是某种社区网站,您可以与Reddit进行比较。因此,也可以对用户发布的帖子进行投票。

现在问题是我无法支持我的帖子。我收到错误:

this._spell.toJSON is not a function.

为了更新我正在使用PUT调用,但我从未在课堂上看过这个,所以我在互联网上搜索并尝试实现它。我与Insomnia的后端电话工作,我的帖子正在上升。但是当我尝试在我的前端调用API时,我收到了这个错误。

我已阅读多个网站并通过Stackoverflow阅读,但仍未找到解决问题的方法。

我的代码

接收事件的post.component代码:

upvote() {
  this.post.upvote();
  this._dndDataService.upvote(this.post.id, this.post).subscribe();
}

Post.Model具有from和toJson

toJSON() {
  return {
    title: this._title,
      originalPoster: this._originalPoster,
      category: this._category,
    comments: this._comments.map(i => i.toJSON()), //fixen indien null
    spell: this._spell.toJSON(),
    dateCreated: this._dateCreated,
    votes: this._votes
  }
}

static fromJSON(json: any): Post {
  const post = new Post(
    json.title,
    json.originalPoster,
    json.category,
    json.spell,
    json.dateCreated
  );
  post._id = json._id;
  post._votes = json.votes;
  post._comments = json.comments.map(Comment.fromJSON); //fixen indien null
  return post;
}

我的dndDataService调用我的后端,这与创建帖子的POST方法几乎相同。我也使用map((p:any) : Post => Post.fromJSON(p)),在这里我没有得到上面提到的错误。

upvote(id: string, post: Post): Observable<Post> {
  const theUrl = `${this._appUrl}/post/${id}/vote`;
  return this.http.put(theUrl, post)
    .pipe(map((p:any) : Post => Post.fromJSON(p)));
}

现在我的后端调用接收整个帖子并更新我的数据库,我使用router.param函数来获取具有正确ID的帖子,这可以用于多种用途:

router.put('/API/post/:id/vote', function (req, res) {
  Post.update({
    $set: {
      votes: req.post}
    },
    function (err, post) {
      if(err)
        res.send("Error updating post");
      res.json(post);
    })    
});

我甚至已经向我的老师发送了有关更新此代码的帮助,但它仍然无效。我真的希望你们中的一些人可以帮助我。

如果您需要我的全部代码,请说出您需要的内容,我会更新我的帖子。

也可以在https://github.com/SFieuws/WebsiteDnd

上找到我的代码

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题,并没有将整个帖子发送到我的后端而只是投票。其次从id获取我的帖子是错误的,因为我打了我的旧票数,这是一个愚蠢的错误。

数据服务

upvoteComment(id: string, points: Number): Observable<Comment> {
  const theUrl = `${this._appUrl}/comments/${id}/vote`;
  return this.http.patch(theUrl, {points})
    .pipe(map((c:any) : Comment => Comment.fromJSON(c)));
}

后端补丁电话

router.patch('/API/post/:post/vote', auth, function (req, res) {
  let query =  Post.findById(req.params.post).populate("comments").populate("spell");
  query.exec(function(err, post){
    if(err) res.send("Post not found");
    post.votes = req.body.votes;
    post.save(function(err, result){
      if(err) res.send("Error updating post"); 
      res.send(post);
    })
  });
});