tjsims8819
tjsims8819

Reputation: 61

Express/mongoose returns empty array when trying to get request

I am trying to get the list of books from the database. I inserted the data on mongoose compass. I only get an empty array back.

//Model File
import mongoose from "mongoose";

const bookSchema = mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  releasedDate: {
    type: String,
    required: true,
  },
});

const Book = mongoose.model("Book", bookSchema);
export default Book;


//Routes file
import express from "express";
import Book from "./bookModel.js";
const router = express.Router();

 router.get("/", async (req, res) => {
   const books = await Book.find({});

   res.status(200).json(books);
 });

Upvotes: 0

Views: 263

Answers (2)

Bhavana guptha
Bhavana guptha

Reputation: 55

make sure you have books data in db.if it is there then try to add then and catch blocks to your code. Then you will get to know what is the error.

await Book.find({})
.then((data) =>{
res.send(data)
})
.catch((err) =>{
res.send(err)
})

Upvotes: 1

Sagar Barapatre
Sagar Barapatre

Reputation: 684

When you create your model, change mongoose.model by new Schema and declare _id attribute like:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const Book = new Schema({
    _id: { type: Schema.ObjectId, auto: true },
    // other attributes
})

Update: If it doesn't seem to work, try changing _id with other names such as bookID or id, that can be the error, read https://github.com/Automattic/mongoose/issues/1285

Upvotes: 0

Related Questions