我如何检查 GET 请求中的空数组并打印自定义消息

How can i check for an empty array in a GET request and print a custom message

我想在数组没有数据时调用 GET 请求时给出自定义消息,而不是仅仅将数组显示为空。

请注意,书籍和作者是不同的 table 并且已链接。我认为这可能是问题所在,但由于它们已链接并且 table 书籍的 GET 请求显示了作者的数组,这让我相信这不是问题所在,但我可能是错的。

我所有的尝试都在安慰数组的消息中有数据,而它显然没有

作者的数组来自数据目录中另一个名为 authors 的文件,但它不显示数据的原因是另一个对这个问题没有帮助的原因。

这里是 GET 函数

    //Get function
const getBooks = async (req, res) => {
  try {
    const books = await Book.find({});
    return res.status(200).json({ success: true, message: 'you have successfuly got all the books ', data: books });
  } catch (err) {
    return res.status(500).json({ success: false,
      msg: err.message || "Something went wrong while getting all books",
    });
  }
}; 

这是 postman 中的获取响应

{
"success": true,
    "message": "you have successfully got all the books ",
    "data": [
        {
            "_id": "625f9334ee0d5550bb041eb2",
            "title": "Animal farm",
            "authors": [],
            "__v": 0
        }

所以响应返回了 id 和标题,还有一个空的作者数组。

我试过了

const getBooks = async (req, res) => {
  try {
    const books = await Book.find({});
    if(authors.length == null){
      console.log("the authors arry is empty")
    }
    else{
      console.log("array has data in it")
    }

以及

//Get function
const getBooks = async (req, res) => {
  try {
    const books = await Book.find({});
    if(!authors.length == null){
      console.log("the authors arry is empty")
    }
    else{
      console.log("array has data in it")
    }

还有这个

const getBooks = async (req, res) => {
  try {
    const books = await Book.find({});
    if(!authors.length){
      console.log("the authors arry is empty")
    }
    else{
      console.log("array has data in it")
    }
    

尝试过

const getBooks = async (req, res) => {
  try {
    const books = await Book.find({});
    if (typeof authors !== 'undefined' && authors.length === 0) {
      console.log("array is empty");
  }
  else{
    console.log("array has data");
  

const getBooks = async (req, res) => {
  try {
    const books = await Book.find({});
    if (typeof authors.length === 0) {
      console.log("array is empty");
  }
  else{
    console.log("array has data");
  

但仍然说它有数据

事实是,如果您的数组为空,!authors.length 应该可以工作。

但我可以看到,您已经使用了 await Book.find({}),因此您将从 db 获得的响应在数组中而不是对象中,因此您的响应结构如下:

[
        {
            "_id": "625f9334ee0d5550bb041eb2",
            "title": "Animal farm",
            "authors": [],
            "__v": 0
        }
]

所以为此你必须检查数组的索引,比如

  const books = await Book.find({});
    if(!books[0].authors.length){
      console.log("the authors arry is empty")
    }

因为我在你的问题中看不到任何地方,作者字段来自哪里,它可能来自 db 调用后的书籍数组。所以尝试这样做,它会解决问题。

const books = [{
  "_id": "625f9334ee0d5550bb041eb2",
  "title": "Animal farm",
  "authors": [],
  "__v": 0
}]

if (!books[0].authors.length) {
  console.log('no author found')
}

如果您有任何疑问,请告诉我。