简体   繁体   中英

Mongoose always returns an empty array in NodeJS

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

藏品名称

数据是什么样的

Here is the results in the console...

在此处输入图片说明

According to Mongoose Documentation if db.connections[0].readyState} returns 1... it means connected Connection Doc

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM