简体   繁体   English

Express/mongoose 在尝试获取请求时返回空数组

[英]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.我在 mongoose 指南针上插入了数据。 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);
 });

make sure you have books data in db.if it is there then try to add then and catch blocks to your code.确保您在 db 中有书籍数据。如果它在那里,请尝试将 then 和 catch 块添加到您的代码中。 Then you will get to know what is the error.然后你就会知道错误是什么。

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

When you create your model, change mongoose.model by new Schema and declare _id attribute like:当您创建 model 时,通过new Schema更改mongoose.model并声明_id属性,例如:

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更新:如果它似乎不起作用,请尝试将_id更改为其他名称,例如bookIDid ,这可能是错误,请阅读https://github.com/Automattic/mongoose/issues/1285

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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