【问题标题】:Update route not working on merged express router params更新路由不适用于合并的快速路由器参数
【发布时间】:2020-02-27 10:22:51
【问题描述】:

我正在学习 MERN 堆栈,但在我的子路由器的编辑路由上遇到了问题。

我在songs.jsstudents.js 文件中有以下模型架构:

const mongoose = require('mongoose');

const studentSchema = mongoose.Schema({
    name: { type: String, required: true },
    instrument: String,
    songs: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Song'
    }]
});

const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
const mongoose = require('mongoose');

const songSchema = mongoose.Schema({
    name: { type: String, required: true },
    img: String
})

const Song = mongoose.model('Song', songSchema);
module.exports = Song

我的路由器有songs.jsstudents.js 文件,我的歌曲路由器const songs = express.Router({ mergeParams: true }); 的mergeParams 设置为true。我像这样将它附加到学生路由器:

students.use('/:id/songs', songs);

例如,我的url参数变成students/student1/songs/song1

我的所有其他路线都在工作,但是在我的歌曲路由器的更新路线上,当我重定向回歌曲的索引视图时,我收到错误“TypeError:Student.findById 不是函数”。我的编辑和更新路线 如下:

songs.get('/:songId/edit', async (req, res) => {
    try {
        const findSong = Song.findById(req.params.songId);
        const findStudent = Student.findById = (req.params.id);
        const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
        res.render('songs/edit', {
            student: foundStudent,
            song: foundSong
        })
    } catch (err) {
        console.log(err);
    }
});

songs.put('/:songId', async (req, res) => {
    try {
        const updateSong = await Song.findByIdAndUpdate(req.params.songId, req.body, { new: true });
        res.redirect('/students/' + req.params.id + '/songs');
    } catch (err) {
        console.log(err);
    }
});

我不确定是什么导致了这里的错误,我的删除路线设置类似并且正在工作。将不胜感激任何建议。

【问题讨论】:

  • '/:songId/edit' 路线不起作用?

标签: node.js express mongoose mern


【解决方案1】:

在你的死记硬背 (req.params.id) 中没有定义。

songs.get('/:songId/edit', async (req, res) => {
    try {
        const findSong = Song.findById(req.params.songId);
        **const findStudent = Student.findById = (req.params.id);**
        const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
        res.render('songs/edit', {
            student: foundStudent,
            song: foundSong
        })
    } catch (err) {
        console.log(err);
    }
});

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 2016-04-14
    • 1970-01-01
    • 2018-01-11
    • 2022-01-24
    • 2018-09-27
    • 1970-01-01
    • 2017-07-03
    相关资源
    最近更新 更多