簡體   English   中英

Mongoose Model.find 總是返回一個空數組

[英]Mongoose Model.find always returning an empty array

我正在使用 mongoose 和 next.js 來訪問現有的集合。

mongoose model.find() 總是返回一個空數組,但集合不為空。

這是我的 model 代碼

const mongoose = require('mongoose');

const ArtistSchema = new mongoose.Schema({});

module.exports = mongoose.models.Artist || mongoose.model('Artist', ArtistSchema, 'artists' );

這是 api 代碼

export default async (req, res) => {
    const { method } = req;

    switch (method) {
        case 'GET':
            try {
               
                const artists = await Artist.find({});

                res.status(200).json({ success: true, data: artists})
            } catch (error) {
                res.status(400).json({ success: false });
            }
            break;
        case 'POST':
            try {
                const artist = await Artist.create(req.body);

                res.status(201).json({ success: true, data: artist })
            } catch (error) {
                res.status(400).json({ success: false });
            }
            break;
        default:
            res.status(400).json({ success: false });
            break;
    }
}

這是收藏的屏幕截圖,它不是空的藝術家收藏屏幕截圖

您必須返回const artists才能獲得您的output

首先,我需要知道你是否連接了 mongo DB atlas,如果沒有在你的 api /index.js中執行此操作,你可以在mongoDB 站點獲取YOUR_MONGO_DB_URL ,然后在/index.js中請求 model

const mongoose = require('mongoose')

mongoose.connect(YOUR_MONGO_DB_URL, {useUnifiedTopology:true, useNewUrlParser:true, autoIndex:false}).then(() => {
    console.log("sucsess");
}).catch((err) => {
    console.log("error:"+err)

require(YOUR_FILE_PATH)
})

在您的 model 文件中,您應該定義索引,例如下面是如何完成的

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ArtistSchema = new Schema({
     name: {
        type : String,
        require: true,
    },
    email: {
        type : String,
        unique : true,
        reqquired : true,
        lowercase : true,
    },
    password : {
        type : String,
        required : true,
        select: false,
    },
    createdAt : {
        type : Date,
        default : Date.now,
    }
});

mongoose.model('Artist', ArtistSchema)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM