Mongodb:业务应用(2)

需求:

1、获取保存到mongodb库中的搜索记录列表

2、实现删除搜索记录接口

保存搜索记录数据参考上篇Mongodb:业务应用(1)_Success___的博客-CSDN博客

获取记录列表

1、创建controller

复制代码
package com.heima.search.controller.v1;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.search.service.ArticleSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/history")
public class SearchHistoryController {
    
    @Autowired
    ArticleSearchService articleSearchService;

    @PostMapping("/load")
    public ResponseResult getHistory(){
        return articleSearchService.getHistory();
    }

}

2、service实现类

复制代码
    /**
     查询搜索历史
     @return
     */
    @Override
    public ResponseResult getHistory() {
        
        //查询当前用户下面的搜索记录
        Integer userId = AppThreadLocalUtil.getUser().getId();
        //构造条件
        Query query = Query.query(Criteria.where("userId").is(userId));
        //执行查询
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        //返回数据
        return ResponseResult.okResult(list);
    }

3、测试

返回成功

根据id删除搜索记录

1、实现controller

复制代码
    @PostMapping("/del")
    public ResponseResult delHistory(@RequestBody ApUserSearch userSearch){
        return articleSearchService.del(userSearch);
    }

2、service实现类

复制代码
    /*根据id删除搜索记录*/
    @Override
    public ResponseResult del(HistorySearchDto dto) {

        //检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //检查登录状态
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //执行删除
        mongoTemplate.remove(Query.query(Criteria.where("userId")
                .is(userId).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

3、测试

相关推荐
阿义有问题7 小时前
MySQL 迁移达梦全流程实战:DTS 七步图解 + 对象名全大写适配(附踩坑清单)
数据库
猫猫不是喵喵.10 小时前
从0到1创建一个微服务项目
java·数据库·微服务·1024程序员节
lsc_blog11 小时前
听到优化风声,先准备能由自己掌控的事
数据库·分布式·中间件·职场和发展·重构
墨痕诉清风11 小时前
SSRF漏洞实战记录+OSS桶命令执行+MCP漏洞
linux·服务器·数据库
Ashe81314 小时前
MySQL 慢日志先别急着加索引:三个指标能拦掉大半误判
数据库
ClouGence14 小时前
最基础的异构数据库 DDL 同步,我们踩过哪些坑?
数据库·mysql·postgresql
羑悻的小杀马特15 小时前
Redis持久化三剑客:RDB二进制快照、AOF文本日志、混合模式如何守护你的数据安全?
数据库·redis·缓存·aof·持久化存储·rdb
小呆爱发呆15 小时前
第三章 MySQL 库表操作
数据库·mysql·adb
时间的拾荒人16 小时前
Redis 进阶实战:渐进式遍历、持久化机制与事务详解
数据库·redis·缓存