MongoDB在SpringBoot中的整合和简单使用

一、引入依赖

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>


#yml配置
spring:
data:
mongodb:
uri: mongodb://localhost:27017/toutiaomongo

二、简单的增删改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class FollowerUserServiceImpl implements FollowUserService {
@Autowired
MongoTemplate mongoTemplate;

@Override
public void follow(Integer userId, Integer followUserId) {
FollowUser followUser = new FollowUser();
followUser.setUserId(userId);
followUser.setFollowUserId(followUserId);
followUser.setId(ObjectId.get());
mongoTemplate.save(followUser);
}

@Override
public void disFollow(Integer userId, Integer followUserId) {
Query query = new Query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
mongoTemplate.remove(query,FollowUser.class);
}

@Override
public boolean isFollow(Integer userId, Integer followUserId) {
Query query = new Query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
List<FollowUser> followUsers = mongoTemplate.find(query, FollowUser.class);
if (followUsers != null && followUsers.size() > 0){
return true;
}
return false;
}
}

三、实现简单的关注逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const isFocus = () => {
console.log("isFocus")
// 判断是否关注
if (user.uid == undefined) {
return;
}
isFollow(user.uid, toutiao.value.uid).then(res => {
if (res == true) {
followLable.value = "已关注"
}
});
}
const focus = () => {
console.log("focus")
if (user.uid == undefined) {
Toast("您未登录!")
return;
}
if (followLable.value == "已关注"){
disFollow(user.uid, toutiao.value.uid)
followLable.value = "关注"
}else {
follow(user.uid, toutiao.value.uid)
followLable.value = "已关注"
}
// isFollow(user.uid, toutiao.value.uid).then(res => {
// if (res == true) {
// disFollow(user.uid, toutiao.value.uid)
// followLable.value = "关注"
// } else {
// follow(user.uid, toutiao.value.uid)
// followLable.value = "已关注"
// }
// });
}

image


MongoDB在SpringBoot中的整合和简单使用
https://yunfreehh.github.io/2023/03/30/MongoDB在SpringBoot中的整合和简单使用/
作者
yunfree
发布于
2023年3月30日
许可协议