【问题标题】:Express/mongoose returns empty array when trying to get requestExpress/mongoose 在尝试获取请求时返回空数组
【发布时间】:2022-02-23 16:58:38
【问题描述】:

我正在尝试从数据库中获取书籍列表。我在猫鼬罗盘上插入了数据。我只得到一个空数组。

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

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    确保您在 db 中有书籍数据。如果存在,请尝试将 then 和 catch 块添加到您的代码中。然后你就会知道错误是什么。

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

    【讨论】:

      【解决方案2】:

      创建模型时,将mongoose.model 更改为new Schema 并声明_id 属性,如:

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

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

      【讨论】:

        猜你喜欢
        • 2018-03-15
        • 1970-01-01
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 2022-06-10
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多