how to reference itself in mongoose schema?

Viewed 20

I am trying to create profile of a user and in friends key I want to store array of objectId of other users. So how to reference itself

const mongoose = require("mongoose")

const userSchema = mongoose.Schema({
    firstname:String,
    lastname:String,
    password:String,
    email:{
        type:String,
        unique:true
    },
    birthday:Date,
    creation_date:{
        type:Date,
        default:Date.now
    },
    gender:String,
    profile_picture:{
        type:String,
        default:""
    },
     friends:[{
         type:mongoose.Schema.Types.ObjectId,
         ref:"userModel"
    }]
})

const userModel = new mongoose.model("userModel", userSchema)
module.exports = userModel

By doing this, and sending request from postman i am getting empty array of friends

 Fields

firstname
dhiran

lastname
sapkota

email
dhiransapkota9@gmail.com

password
thisisemail

birthday
2059-08-09

gender
male

friends
["6319b1bd2d4f0f0145662f3b", "6319ad712d4f0f0145662f35"]

Output I am getting is:

{
  "success": true,
  "msg": "user has been signed up",
  "signupUser": {
    "firstname": "dhiran",
    "lastname": "sapkota",
    "password": "$2a$10$rOaA3QlameBO4my8C9fmye73Zi9QxtPbi3X.XFpDNd7J8tBD3SbMq",
    "email": "dhiransapkota999@gmail.com",
    "birthday": "2059-08-09T00:00:00.000Z",
    "gender": "male",
    "profile_picture": "1662798667954-cv_image.png",
    "friends": [],
    "_id": "631c4b4c2d832a439c88720f",
    "creation_date": "2022-09-10T08:31:08.072Z",
    "__v": 0
  }
}

I am using multipart/formdata so data is in this format.

route

router.post("/signup", upload.single("profile"), (req, res) => {
    userControllerInstance.signup(req, res, profile_picture)
});

controller:

class UserController {
  async signup(req, res, profile_picture) {
    try {
      const { firstname, lastname, email, password, birthday, gender, friends } =
        req.body;
      const response = await userModel.find({ email: email });
      console.log(response);
      if (response.length > 0) {
        return res
          .status(409)
          .json({ success: false, msg: "email already exists" });
      }

      const hashedPassword = generateHash(password);

      const signupUser = await userModel.create({
        firstname,
        lastname,
        email,
        password: hashedPassword,
        birthday,
        gender,
        profile_picture,
         friends
      });
      return res.json({
        success: true,
        msg: "user has been signed up",
        signupUser,
      });
    } catch (error) {
      return res.json(error);
    }
  }
}
0 Answers
Related