-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
91 lines (81 loc) · 2.69 KB
/
user.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//jshint esversion:6
const express = require("express");
const router = express.Router();
const mongoose = require('mongoose');
const requireLogin=require("../middleware/requireLogin");
const Recipe=mongoose.model("Recipe");
const User = mongoose.model("User");
router.get('/user/:id',requireLogin,(req,res)=>{ // here we get the "id" of the user along with url , whose profile we want to see
User.findOne({_id:req.params.id}) // query to find the user using "id" in "User" db
.select("-password") // select all the field except password
.then(user=>{
Recipe.find({postedBy:req.params.id}) // if user exist then find the recipes of that user // or query for find the recipes of that user
.populate("postedBy","_id name")
.exec((err,recipes)=>{
if(err){
return res.status(422).json({error:err})
}
res.json({user,recipes})
})
}).catch(err=>{
return res.status(404).json({error:"User not found"})
})
})
router.put('/follow',requireLogin,(req,res)=>{
User.findByIdAndUpdate(req.body.followId,{
$push:{followers:req.user._id}
},{
new:true
},(err,result)=>{
if(err){
return res.status(422).json({error:err})
}
User.findByIdAndUpdate(req.user._id,{
$push:{following:req.body.followId}
},{new:true}).select("-password").then(result=>{
res.json(result)
}).catch(err=>{
return res.status(422).json({error:err})
})
}
)
})
router.put('/unfollow',requireLogin,(req,res)=>{
User.findByIdAndUpdate(req.body.unfollowId,{
$pull:{followers:req.user._id}
},{
new:true
},(err,result)=>{
if(err){
return res.status(422).json({error:err})
}
User.findByIdAndUpdate(req.user._id,{
$pull:{following:req.body.unfollowId}
},{new:true}).select("-password").then(result=>{
res.json(result)
}).catch(err=>{
return res.status(422).json({error:err})
})
}
)
})
router.post('/search-users',(req,res)=>{
let userPattern = new RegExp("^"+req.body.query)
User.find({name:{$regex:userPattern}})
.select("_id name")
.then(user=>{
res.json({user})
}).catch(err=>{
console.log(err)
})
})
router.put('/updatepic',requireLogin,(req,res)=>{
User.findByIdAndUpdate(req.user._id,{$set:{pic:req.body.pic}},{new:true},
(err,result)=>{
if(err){
return res.status(422).json({error:"pic cannot post"})
}
res.json(result)
})
})
module.exports=router;