我想在陣列沒有資料時呼叫 GET 請求時提供自定義訊息,而不是僅將陣列顯示為空。
請注意,書籍和作者是不同的表并且是鏈接的。我認為這可能是問題,但由于它們是鏈接的,并且對表格書籍的 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",
});
}
};
這是郵遞員的回復
{
"success": true,
"message": "you have successfully got all the books ",
"data": [
{
"_id": "625f9334ee0d5550bb041eb2",
"title": "Animal farm",
"authors": [],
"__v": 0
}
所以回應回傳了 id 和 title 以及一個空的作者陣列。
我試過了
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");
但仍然說它有資料
uj5u.com熱心網友回復:
問題是,!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')
}
如果您有任何疑問,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459239.html
標籤:javascript 表示 猫鼬
