-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproductRoute.js
71 lines (58 loc) · 1.79 KB
/
productRoute.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
const express = require("express");
const { default: mongoose } = require("mongoose");
const Product = require("../models/addPropertyModel");
const Like = require("../models/likes");
const User = require("../models/userModel");
const router = express.Router();
router.get("/", async function (req, res) {
try {
const allProds = await Product.find({}).populate("user").exec();
// allProds = await Promise.all(
// allProds.map(async function (p) {
// p.populate("user");
// await p.execPopulate();
// return p;
// })
// );
return res.json({ products: allProds });
} catch (e) {
return res.json({ error: e.toString() });
}
});
router.post("/like/:productId/:userId", async function (req, res) {
console.log(req.params);
try {
const user = await User.findById(req.params.userId);
const product = await Product.findById(req.params.productId);
if (!user || !product) throw new Error("User or product not found");
const alreadyLiked = await Like.countDocuments({
user: user._id,
product: product._id,
});
if (alreadyLiked != 0) {
return res.send({ alreadyLiked: true });
} else {
const like = await Like.create({ user: user._id, product: product._id });
return res.send(like);
}
} catch (e) {
return res.json({ error: e.toString() });
}
});
router.get("/notifications/:userId", async function (req, res) {
try {
const products = await Product.find(
{ user: mongoose.Types.ObjectId(req.params.userId) },
"_id"
);
const likes = await Like.find({
product: { $in: products.map((p) => p._id) },
}).populate("user product");
return res.json(likes);
} catch (e) {
return res.json({
error: e.toString(),
});
}
});
module.exports = router;