MongoDB return empty array next js

Viewed 34

I have try a lot to find the reason of why i am getting empty array but failed.I have tried with every ways but could not able to fix it. I have attached my two file below . collection name is "product".

import mongoose from "mongoose";

const productSchema = new mongoose.Schema({
  img: {
    type: "String",
    required: false,
  },
  category: {
    type: "String",
    required: false,
  },
  price: {
    type: "String",
    required: false,
  },
  description: {
    type: "String",
    required: false,
  },
  heading: {
    type: "String",
    required: false,
  },
  available: {
    type: "Boolean",
    required: false,
  },
});
export default mongoose.model("products", productSchema);


//src/api
import connectMongo from "../../lib/mongodb";
import products from "../../models/products";

export default async function handler(req, res) {
  try {
    await connectMongo();
    let response = await products.find();
    res.status(200).json(response);
  } catch (err) {
    console.log(err);
    res.status(err).json([]);
  }
}

//connectMongo file

import mongoose from "mongoose";

const connectMongo = async () =>
  mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true });

export default connectMongo;
0 Answers
Related