返回嵌入式集合mongodb spring boot时未找到

zxlwwiss  于 2021-07-15  发布在  Java
关注(0)|答案(3)|浏览(299)

我正在用springdatarest和mongodb在课程文档中创建一个嵌入了复习文档的应用程序,但是我无法获得课程的复习。这是我的控制器:

@Controller
@RequestMapping("/courses")
public class CourseController {

    private final CourseRepository courseRepository;

    public CourseController(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    @PatchMapping("/add-review")
    public List<Review> addReview(@RequestBody AddReviewDto addReviewDto) {
        Course course = courseRepository.findById(addReviewDto.getCourseId()).get();
        Review review = new Review(new ObjectId().toString(), addReviewDto.getReview());

        List<Review> reviews = course.getReviews();
        reviews.add(review);

        course.setReviews(reviews);

        return courseRepository.save(course).getReviews();
    }

    @GetMapping("/{id}/reviews")
    public List<Review> getAllReviewsForCourse(@PathVariable String id) {
        Course course = courseRepository.findById(id).get();

        return course.getReviews();
    }
}

以下是课程模式:

@Getter
@Setter
@Document(collection = "courses")
@AllArgsConstructor
@NoArgsConstructor
public class Course {

    public Course(@NotNull String code, @NotNull String name,
                  @NotNull String type, List<Review> reviews) {
        this.code = code;
        this.name = name;
        this.type = type;
        this.reviews = reviews;
    }

    @Id
    private String id;

    @NotNull
    private String code;

    @NotNull
    private String name;

    @NotNull
    private String type;

    private List<Review> reviews = new ArrayList<>();
}

审查模式:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Review {

    @Id
    private String id;

    private String reviewText;

    private String userName;

    private String userId;

    public Review(String id, Review other) {
        this.id = id;
        this.reviewText = other.reviewText;
        this.userId = other.userId;
        this.userName = other.userName;
    }
}

当我向发送请求时http://localhost:8888/courses/605dc41f54beac4412cabadc,我成功地在course对象内获得了评论,如下所示:

{
  "code": "CS 101",
  "name": "Introduction to Programming",
  "type": "Lecture",
  "reviews": [
    {
      "reviewText": "dfgsfgdgdg",
      "userName": "yigit",
      "userId": "604a9382777a83b08307c7e8"
    }
  ]
}

但是当我试图把请求发送到localhost:8888/courses/605dc41f54beac4412cabadc/reviews,我找不到404。
我调试了我的代码,发现代码运行的是正确的控制器,发现课程对象及其评论在调试器中可见,但当我返回course.getreviews()时,它不起作用。

woobm2wo

woobm2wo1#

你应该把 http://localhost:8888/courses/605dc41f54beac4412cabadc/reviews 尝试在浏览器中打开此url

y1aodyip

y1aodyip2#

当然是404。因为您的@requestmapping是“/课程”。尝试将请求发送到 http://localhost:8888/courses/{id}/reviews

jljoyd4f

jljoyd4f3#

原来,我用了@controller而不是@restcontroller。。。

相关问题