Home > front end >  Mongoose always returns an empty array in NodeJS
Mongoose always returns an empty array in NodeJS

Time:11-19

I am trying to pull all the products of of the products collection on MongoDB Atlas. All I get in return are empty arrays.

I have a proper connection to the database.

I am unsure about the model and how I am using Mongoose.

Here is my connection... connectDb.js

import mongoose from "mongoose";
const connection = {};

async function connectDb() {
  if (connection.isConnected) {
    console.log("Connection in progress");
    return;
  }
  const db = await mongoose.connect(process.env.MONGO_SRV, {
    useCreateIndex: true,
    useFindAndModify: false,
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  console.log("DB Connected");
  connection.isConnected = db.connections[0].readyState;
}

export default connectDb;

Here is my schema... ./models/Product.js

import mongoose from "mongoose";
import shortid from "shortid";

const { String, Number } = mongoose.Schema.Types;

const ProductSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  sku: {
    type: String,
    unique: true,
    required: true,
    default: shortid.generate(),
  },
  mediaUrl: {
    type: String,
    required: true,
  },
});

// Check for an existing `models.Product` ... then run the product schema
export default mongoose.models.Product ||
  mongoose.model("products", ProductSchema);

Here is my query ... ./api/products.js

import Product from "../../models/Product";
import connectDb from "../../utils/connectDb";

connectDb();

export default async (req, res) => {
  const products = await Product.find({});
  console.log(`products are ... ${products}`);
  res.status(200).json(products);
};

Here is my database

name of collection

what the data looks like

Here is the results in the console...

enter image description here

According to Mongoose Documentation if db.connections[0].readyState} returns 1... it means connected enter image description here

CodePudding user response:

Check your env var MONGO_SRV. Make sure that your connection URL is with the relevant DB.

  • Related