How to access nested elements of json object in node js and mongodb

100 views Asked by At
const mongoose = require("mongoose");

const productSchema = mongoose.Schema({
  product_name: {
    type: String,
    required: [true, "Must Enter Product Name"],
  },
  product_brand: {
    type: String,
  },
  category: {
    type: String,
    required: [true, "Must Enter Product Catagorey"],
  },
  reviews: [
    {
      name: {
        type: String,
      },
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
      comment: {
        type: String,
        required: true,
      },
      rating: {
        type: Number,
        // required: true,
      },
    },
    { timestamps: true },
  ],

  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
});

module.exports = mongoose.model("Product", productSchema);

Here I want to access the values of commet for Appling filters

Here is is the output of my products

[
  {
    "_id": "63c4ee520ca7722674d007d5",
    "product_name": "Headphones",
    "product_description": "xvy",
    "product_price": 8000,
    "product_brand": "Apple",
    "product_color": "White",
    "product_stoke": 3,
    "category": "Headphones",
    "product_image": "public\\images\\uploaded\\products\\167385045002297820433-5f2f-43d1-972a-4b33785393ee.0ad829318c5599f429d2a6e625f8bde3.jpeg",
    "product_sku": "#1",
    "owner": "63c4ed720ca7722674d007ab",
    "reviews": [
      {
        "name": "Daniyal Alam",
        "user": "63c43d54cf582066929c8c46",
        "comment": "Good Mobbile Phone",
        "rating": 4,
        "_id": "63cbce2cd52bf9ecfdf29323"
      }
    ],
    "__v": 1
  },
  {
    "_id": "63c4e3530ca7722674d006b6",
    "product_name": "Air bud Two.",
    "product_description": "In the busy world which is fil.",
    "product_price": 50000,
    "product_brand": "Apple",
    "product_color": "White",
    "product_stoke": 5,
    "category": "Headphones",
    "product_image": "public\\images\\uploaded\\products\\167384763581197820433-5f2f-43d1-972a-4b33785393ee.0ad829318c5599f429d2a6e625f8bde3.jpeg",
    "product_sku": "33",
    "owner": "63c4d8ac0ca7722674d00529",
    "reviews": [],
    "__v": 0
  },
]

I want to access my comments I tried the following code but it only returns reviews

exports.commentProduct = async (req, res, next) => {
  const newproduct = await Product.find({});
  try {
    const reviews = newproduct?.map((p) => {
      if (typeof p.reviews != "undefined") {
        console.log(p.reviews);
      }
    });
    const com = reviews?.map((c) => {
      // console.log(comments);
    });

    // const comments = reviews.comment;
    return res.status(200).json({
      success: true,
      reviews,
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: error.message,
    });
  }
};

the Console Prints products having reviews but after applying dot notation on reviews I got undefined

[
  {
    name: 'Daniyal Alam',
    user: new ObjectId("63c43d54cf582066929c8c46"),
    comment: 'BEst One',
    rating: 5,
    _id: new ObjectId("63cbce44d52bf9ecfdf29743")
  }
]
[]
[]
[]
[]
[]
[]
[]
[]
[
  {
    name: 'Daniyal Alam',
    user: new ObjectId("63c43d54cf582066929c8c46"),
    comment: 'pp',
    rating: 4,
    _id: new ObjectId("63c4f76e0ca7722674d040ae")
  }
]
[]
[
  {
    name: 'Daniyal Alam',
    user: new ObjectId("63c43d54cf582066929c8c46"),
    comment: 'Good Mobbile Phone',
    rating: 4,
    _id: new ObjectId("63cbce2cd52bf9ecfdf29323")
  }
]
1

There are 1 answers

0
Burham B. Soliman On

Working with your example, you can map each item, then map the reviews, and get the comment out of each like using the following code

const data = [{ 
  "_id": "63c4ee520ca7722674d007d5",
  "product_name": "Headphones",
  "product_description": "xvy",
  "product_price": 8000,
  "product_brand": "Apple",
  "product_color": "White",
  "product_stoke": 3,
  "category": "Headphones",
  "product_image": "public\\images\\uploaded\\products\\167385045002297820433-5f2f-43d1-972a-4b33785393ee.0ad829318c5599f429d2a6e625f8bde3.jpeg",
  "product_sku": "#1",
  "owner": "63c4ed720ca7722674d007ab",
  "reviews": [{
    "name": "Daniyal Alam",
    "user": "63c43d54cf582066929c8c46",
    "comment": "Good Mobbile Phone",
    "rating": 4,
    "_id": "63cbce2cd52bf9ecfdf29323"
   }],
  "__v": 1 
}]

data.map((dat) => {
  dat["reviews"].map((rev) => {
    document.querySelector('div').innerHTML +=rev["comment"]
  })
})
<div></div>