Populate from an array in MongoDB

PHOTO EMBED

Sun Mar 20 2022 11:24:15 GMT+0000 (Coordinated Universal Time)

Saved by @youngDumb #mongo #nodejs

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema.Types;

const reviewSchema = new Schema(
  {
    productId: {
      type: ObjectId,
      ref: "Product",
    },
    reviews: [
      {
        userId: {
          type: ObjectId,
          ref: "User",
        },
        rating: {
          type: Number,
          required: true,
        },
        comment: {
          type: String,
        },
      },
    ],
    totalRate: {
      type: Number,
      default: 0,
    },
  },
  { timestamps: true }
);

router.get("/:id", (req, res) => {
  Review.findOne({ productId: req.params.id })
    .populate({
      path: "reviews",
      populate: { path: "userId", select: "-_id username" },
    })        
    .then((reviews) => {      
        res.status(200).json(reviews);      
    })
    .catch((err) => res.status(500).json(err));
});
content_copyCOPY