Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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);
 });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)
})
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda