Creating references between schemas in MongoDB and queries to get the data from the same

25 views Asked by At

Here are the two schemas I am using: UserSchema

import mongoose from "mongoose";
const UserSchema = new mongoose.Schema(
  {
    _id: {
      type: Schema.Types.ObjectId,
    },
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      // match: /.+\@.+\..+/,
      unique: true,
    },
    phoneNumber: {
      type: String,
      unique: true,
    },
    image: {
      type: String,
    },
    password: {
      type: String,
      unique: true,
      required: true,
    },
    tokens: [{ type: Object }],
    code: String,
    accountType: {
      type: String,
    },
    isAdmin: {
      type: Boolean,
      default: false,
    },
    location: {
      type: String,
    },
    coords: { type: Object },
    isEditor: {
      type: Boolean,
      default: false,
    },
    isVerified: {
      type: Boolean,
      default: false,
    },
    isSuspended: {
      type: Boolean,
      default: false,
    },
  },
  { timestamps: true }
);

export default mongoose.model("User", UserSchema);

ReviewsSchema

import mongoose from "mongoose";

const ReviewsSchema = new mongoose.Schema(
  {
    writer: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
    body: {
      type: String,
      required: true,
    },
    rating: {
      type: Number,
      required: true,
    },
  },
  { timestamps: true }
);

export default mongoose.model("Reviews", ReviewsSchema);

How do I create a controller function to fetch reviews associated with a certain user?

Below is the controller function I am using to fetch a single review: reviewController.js

export const getReview = async (req, res, next) => {
  try {
      const review = await Reviews.findById(req.params.id);
      res.status(200).json({ success: true, review });
    } catch (err) {
      next(err);
    }
};

When I test the api endpoint using Postman, below is the result I am getting:

{
"success": true,
"review": {
    "_id": "654c2568df670257734ee11c",
    "body": "MechLocator has helped me big time",
    "rating": 0.95,
    "createdAt": "2023-11-09T00:18:48.080Z",
    "updatedAt": "2023-11-09T00:18:48.080Z",
    "__v": 0
}

}

As you can see, I didn't get the writer field populated from the call to my server. I expected to see this field populated with the ObjectId of the user who is associated with this review.

What am I not doing right?

0

There are 0 answers