Home > Software design >  How to show categories name with mongodb relationships
How to show categories name with mongodb relationships

Time:09-11

i wanna show categories name in that view who users can see it beside product actually in single page view of product but i think i have some problems in relationships of mongo because it just return an empty array! i will appreciate if you help me

product model :

const createProductSchema = Schema(
  {
    user: { type: Schema.Types.ObjectId, ref: "User" },
    categories: [{ type: Schema.Types.ObjectId, ref: "Category" }],
    title: { type: String, required: true },
    type: { type: String, required: true },
    slug: { type: String, required: true },
    body: { type: String, required: true },
    images: { type: Object, required: true },
    thumb: { type: String, required: true },
    price: { type: String, required: true },
    tags: { type: String, required: true },
    viewCount: { type: Number, default: 0 },
  },
  { timestamps: true, toJSON: { virtuals: true } }
);

createProductSchema.virtual("category", {
  ref: "Category",
  localField: "_id",
  foreignField: "products",
});

category model :

const categorySchema = Schema(
  {
    products: [{type:  Schema.Types.ObjectId, ref: "Product" }],
    name: { type: String, required: true },
    slug: { type: String, required: true },
    parent: { type: Schema.Types.ObjectId, ref: "Category", default: null },
  },
  { timestamps: true, toJSON: { virtuals: true } }
);

productController:

 let product = await Product.findOne({ slug: req.params.product })
      .populate([
        {
          path: "user",
          select: "name",
        },
        {
          path:"category",
          select:"name",
        }
      ]);
    res.json(product);

and in output i just can see category:[]
:((((((

CodePudding user response:

You should populate categories, not category:

let product = await Product.findOne({ slug: req.params.product })
  .populate([
    {
      path: 'user',
      select: 'name',
    },
    {
      path: 'categories',
      select: 'name',
    },
  ])
  .exec();
res.json(product);
  • Related