profile.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import mongoose from "mongoose";
  2. import Profile from "../models/profile.js";
  3. export const getProfiles = async (req, res) => {
  4. try {
  5. const users = await Profile.find().populate("user", ["name", "avatar"]);
  6. res.status(200).json(users.reverse());
  7. } catch (error) {
  8. res.status(404).json({ message: error.message });
  9. }
  10. };
  11. export const getProfile = async (req, res) => {
  12. try {
  13. const profile = await Profile.findOne({
  14. user: req.userId,
  15. }).populate("user", ["name", "avatar"]);
  16. if (!profile) {
  17. return res.status(400).json({ msg: "There is no profile for this user" });
  18. }
  19. res.json(profile);
  20. } catch (err) {
  21. console.error(err.message);
  22. res.status(500).send("Server Error");
  23. }
  24. };
  25. export const updateProfile = async (req, res) => {
  26. const { bio, age, contacts } = req.body;
  27. if (!mongoose.Types.ObjectId.isValid(req.userId)) {
  28. return res.status(404).send("No profile with that id");
  29. }
  30. const updatedProfile = { bio, age, contacts, _id: req.userId };
  31. console.log(updatedProfile);
  32. await Profile.findByIdAndUpdate(
  33. {
  34. user: req.userId,
  35. },
  36. updatedProfile,
  37. { new: true }
  38. ).populate("user", ["name", "avatar"]);
  39. res.json(updatedProfile);
  40. };