mongodb MondoDB上的文档未被读取,使用Mongoose

xzlaal3s  于 2023-03-01  发布在  Go
关注(0)|答案(1)|浏览(103)

尝试询问ChatGPT,但似乎旧的时尚方式总是最好的...
我想我的架构、控制器和路由都是正确的,但当我访问http://localhost:8080/api/v1/album时,它一直说在我的控制台中找到0个文档。我不确定这里出了什么问题,架构对我上传的文档似乎是正确的。
Index.js:

import express from 'express';
import connectDB from './mongodb/connect.js';
import cors from 'cors';

import * as dotenv from 'dotenv';

import userRouter from './mongodb/routes/user.routes.js'
import albumRouter from './mongodb/routes/album.routes.js'

// ** configs
dotenv.config();

const app = express();
app.use(express.json());
app.use(express.urlencoded());

app.get('/', (req, res) => {
    res.send({ message: "Hello" })
})

app.use('/api/v1/users', userRouter);
app.use('/api/v1/album', albumRouter);

const serverInit = async () => {
    try {
        connectDB(process.env.MONGODB_URL);
        app.listen(8080, console.log('server on 8080'))
    } catch (error) {
        console.log(error)
    }
}

serverInit();

album.js架构:

import mongoose, { Schema } from "mongoose";

const AlbumSchema = new mongoose.Schema({
    album_id: {type: String, required: true},
    title: {type: String, required: true},
    artist: {type: String, required: true},
    label: {type: String, required: true},
    genre: {type: String, required: true},
    khz: {type: Number, required: true},
    bitrate: {type: Number, required: true},
    numTracks: {type: Number, required: true},
    runtime: {type: Number, required: true},
    parental: {type: Boolean, required: true},
}, { collection: 'app-data.albums' })

const albumModel = mongoose.model('Album', AlbumSchema)

export default albumModel;

album.routes.js:

import express from 'express';

import {
    getAllAlbums,
    getAlbumDetail
} from '../controllers/album.controller.js'

const router = express.Router();

router.route('/').get(getAllAlbums)
router.route('/:id').get(getAlbumDetail)

export default router;

最后,控制器:

import User from '../models/user.js'
import Album from '../models/album.js'

import * as dotenv from 'dotenv'

dotenv.config();

const getAllAlbums = async (req, res) => {
    try {
        console.log('Retrieving all albums from the app-data.albums collection...');
        const albums = await Album.find({}).limit(req.query._end)  //find all albums in db

        console.log(`Found ${albums.length} albums`);

        res.status(200).json(albums)
    } catch (error) {
        res.status(500).json({ msg: error.message })
    }
}; 

const getAlbumDetail = async (req, res) => {}; 

export {
    getAllAlbums,
    getAlbumDetail
}

以下是上传的文档:
mongodb document
我真的希望这不是矫枉过正,我只是不知道如何得到帮助,而不张贴所有这些。有人有什么想法吗?

uurv41yg

uurv41yg1#

没关系,我发现了这个问题。这仅仅是因为我在网站上有第二个集合,它指的是相反,我忘记了我做了,我现在只想哭...我必须审查代码,看看为什么这个特定的集合比其他的优先。

相关问题