Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with update a single doc in monogdb using express and mongoose

I’m quiet new to mongodb and I’m actually trying to implement a follow-unfollow method in the backend
there are two types of users in the database

Mentors and mentees

only mentees can follow the mentors and mentors can only accept the request

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the schema

Mentors

const MentorsSchema = mongoose.Schema({
  name: { type: String, required: true },
  designation: { type: String, required: true },
  yearNdClass: {
    type: String,
    required: ["true", "year and class must be spciefied"],
  },
  respondIn: { type: String, required: true },
  tags: {
    type: [String],
    validate: (v) => v == null || v.length > 0,
  },
  socialLinks: {
    github: { type: String, default: "" },
    twitter: { type: String, default: "" },
    facebook: { type: String, default: "" },
    instagram: { type: String, default: "" },
  },
  watNum: { type: Number, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  about: { type: String },
  followers: [
    { type: mongoose.Schema.Types.ObjectId, ref: "Mentees", default: "" },
  ],
  pending: [
    { type: mongoose.Schema.Types.ObjectId, ref: "Mentees", default: "" },
  ],
});

Mentee

const MenteeSchema = mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  yearNdClass: {
    type: String,
    required: ["true", "year and class must be spciefied"],
  },
  socialLinks: {
    github: { type: String },
    twitter: { type: String },
    facebook: { type: String },
    instagram: { type: String },
  },
  about: { type: String },
  skillLooksFor: { type: String, required: true },
  watNum: { type: Number, required: true },
  following: [{ type: mongoose.Schema.Types.ObjectId, ref: "Mentors",default:"" },
  
],
});

you can see that there are two fields for mentors both following and pending arrays which consist of the ids of the mentees who follow the mentors and the ids of the mentees which yet to be accepted as a follower

I planned to create an endpoint where when a mentee gives a follow request it should be reached into the mentor pending array so that he can accept it later

so my logic like this

// @desc follow a mentor
// @route POST /api/mentees/follow-mentor/:id
// @access private

menteeRoute.post(
  "/follow-mentor/:id",
  isAuthorisedMentee,
  expressAsyncHandler(async (req, res) => {
    const { id } = req.params;
    const mentee = await Mentees.findById(req.mentee.id);
    const mentor = await Mentors.findById(id).select("-password");
    // console.log(mentor)
    if (mentee) {
      try {
        await Mentees.findOneAndUpdate(
          { _id: mongoose.Types.ObjectId(id) },
          { $addToSet: { "following.0": mentor._id } },
          { new: true }
        );

        await Mentors.findOneAndUpdate(
          { _id: mongoose.Types.ObjectId(mentor._id) },
          {
            $addToSet: {
              "pending.0": id,
            },
          },
          { new: true },
        );

        res.json({
          data: {
            mentor,
            mentee,
          },
        });
      } catch (error) {
        console.log(error);
        throw new Error(error);
      }
    }
  })
);

but the code didn’t work.
can anyone help me to resolve the problem?

basically, when a mentee gives a follow request it should update the following array of mentee with the id of mentor and it should also update the pending array of mentor with the id of the mentee

PS: any alternative ideas are also welcome

>Solution :

Try to remove the .0 index and use the $push method.
Also, you should return the updated objects:

menteeRoute.post(
  '/follow-mentor/:id',
  isAuthorisedMentee,
  expressAsyncHandler(async (req, res) => {
    const { id } = req.params;
    const mentee = await Mentees.findById(req.mentee.id);
    const mentor = await Mentors.findById(id).select('-password');
    // console.log(mentor)
    if (mentee) {
      try {
        const updatedMentee = await Mentees.findOneAndUpdate(
          { _id: mongoose.Types.ObjectId(id) },
          { $push: { following: mentor._id } },
          { new: true }
        );

        const updatedMentor = await Mentors.findOneAndUpdate(
          { _id: mentor._id },
          {
            $push: {
              pending: id,
            },
          },
          { new: true }
        );

        res.json({
          data: {
            mentor: updatedMentor,
            mentee: updatedMentee,
          },
        });
      } catch (error) {
        console.log(error);
        throw new Error(error);
      }
    }
  })
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading