I am creating a e-commerce app and now I want to get all the review of a product using nodejs and database is mongoDB (using mongoose). This is my Schemas:
User Schema:
const userSchema = new Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, required: true, default: false },
},
{
timestamps: true,
}
);
Product Schema:
const productSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
required: true,
ref: "users",
},
name: { type: String, required: true },
image: { type: String, required: true },
brand: { type: String, required: true },
category: { type: String, required: true },
description: { type: String, required: true },
reviews: [
{
name: { type: String, required: true },
rating: { type: Number, required: true },
comment: { type: String, required: true },
user: {
type: Schema.Types.ObjectId,
required: true,
ref: "users",
},
},
{
timestamps: true,
},
],
rating: { type: Number, required: true, default: 0 },
reviewNumber: { type: Number, required: true, default: 0 },
price: { type: Number, required: true, default: 0 },
countInStock: { type: Number, required: true, default: 0 },
});
I want to get all reviews of a product. It's my controller
//* desc Get all reviews
//* route GET /product/:id/review
//* access Public
const getAllReviews = async (req, res) => {
try {
const product = await Product.findById(req.params.id);
const reviews = product.reviews.find({});
return res.status(200).json({
success: true,
reviews,
});
} catch (error) {
console.log(error);
return res.status(500).json({
success: false,
message: "Internal server error",
});
}
};
But when I test by using Postman. The result is error 500. How can I get all review?
Error:
TypeError: #<Object> is not a function
at Proxy.find (<anonymous>)
at getAllReviews (D:\Workspace\Projects\e-commerce\server\src\controllers\product.controller.js:210:37)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
CodePudding user response:
If you want to send all the reviews for the product, you don't need to add this line
const reviews = product.reviews.find({});
You can simply type
const reviews=product.reviews;