Home > Enterprise >  Express/mongoose returns empty array when trying to get request
Express/mongoose returns empty array when trying to get request

Time:02-23

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);
 });

CodePudding user response:

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)
})

CodePudding user response:

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

  • Related