首页 > 解决方案 > MEAN- mongoose - 获取子文档的父 ID(返回未定义)

问题描述

我在使用我的角度服务填充子文档时遇到了一些问题

我试过邮递员,我认为我从后端得到了正确的结果......

问题是:

获取文章评论的 API 端点

//get all comments for an article
router.get('/:articleId/comments', function (req, res, next) {
    Article.findOne({ _id: req.params.articleId })
        .populate('article, articleId')
        .populate('comments')
        .exec(function (err, comments) {
            if (err) {
                return res.status(500).json({
                    title: 'An error occured getting the articles\'s comment',
                    error: err
                });
            }
            res.status(200).json({
                message: 'Succesfull',
                obj: comments
            });
        });
});

我的文章服务获取每篇文章的评论

    getComments() {
        const articleId = this.activatedRoute.snapshot.params['articleId'];
        return this.http.get('http://localhost:7777/article/' + articleId + '/comments')
            .map((response: Response) => {
                const comments = response.json().obj;
                const transformedComments: Comment[] = [];
                for (const comment of comments) {
                    transformedComments.push(new Comment(
                        comment.body,
                        comment.username,
                        comment._id,
                        comment.articleId
                    ));
                }
                this.comments = transformedComments;
                console.log(transformedComments);
                return transformedComments;
            })
            .catch((error: Response) => Observable.throw(error.json()));
    }

邮递员请求的响应

http://localhost:7777/article/5b1d0659cee09b0ca4d79147/comments 


{
    "message": "Succesfull",
    "obj": {
        "comments": [
            {
                "_id": "5b1d0674cee09b0ca4d79148",
                "body": "how about it scoffield",
                "username": "McAndi",
                "articleId": "5b1d0659cee09b0ca4d79147",
                "__v": 0
            },
            {
                "_id": "5b1d1129cf9e7830a80bbf9c",
                "body": "shes feeling me down below",
                "username": "McAndi",
                "articleId": "5b1d0659cee09b0ca4d79147",
                "__v": 0
            },
            {
                "_id": "5b1d1e57df754307e45d4ef4",
                "body": "slay mamas won yapa sibe",
                "username": "McAndi",
                "articleId": "5b1d0659cee09b0ca4d79147",
                "__v": 0
            }
        ],
        "favoritesCount": 69,
        "_id": "5b1d0659cee09b0ca4d79147",
        "title": "Jaded",
        "description": "Ejanla Surface, the koko is loaded, infact the gbedu has landed ✈",
        "body": "Ejanla Surface, the koko is loaded, infact the gbedu has landed ✈Ejanla Surface, the koko is loaded, infact the gbedu has landed ✈",
        "username": "McAndi",
        "userId": "5b1735fe5821ba1fe801d5ba",
        "__v": 3
    }
}

我使用该getComments()服务的文章评论组件

import { Component, OnInit, ViewEncapsulation, Input } from '@angular/core';

import { ArticleService } from '../../article.service';
import { User } from '../../../auth/user.model';
import { Comment } from '../../comment.model';

@Component({
  selector: 'app-article-comment-list',
  templateUrl: './article-comment-list.component.html',
  styleUrls: ['./article-comment-list.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class ArticleCommentListComponent implements OnInit {
  private User: any;
  article: any;

  constructor(private articleService: ArticleService, ) { }

  comments: Comment[];
  ngOnInit() {
    this.articleService.getComments()
      .subscribe(
        (comments: Comment[]) => {
          this.comments = comments;
        });
  }

在我的应用程序中,如果我应该导航到:articleId/comments,则articleId变为未定义......这是我现在遇到的主要问题`下面是来自控制台的错误结果

{title: "An error occured getting the articles's comment", error: {…}}
error
:
kind
:
"ObjectId"
message
:
"Cast to ObjectId failed for value "undefined" at path "_id" for model "Article""
name
:
"CastError"
path
:
"_id"
stringValue
:
""undefined""
value
:
"undefined"
__proto__
:
Object
title
:
"An error occured getting the articles's comment"
__proto__
:
Object

我浏览器中的网址变为

http://localhost:7777/article/undefined/comments

我实际上不能说这是错误或错误所在,但任何提醒都会非常感激......谢谢。

标签: javascriptangular

解决方案


推荐阅读