关于express URL传递参数的疑问 Nodejs

关于express URL传递参数的疑问 Nodejs

我用mongoose, 练习写一个博客,我想删除父文档的一个文章下的子文档中的一条评论,那URL就要传两个ID才能找到,怎样才能传两个参数呢?或者怎么更好的解决这个问题呢?

6 回复

当然可以。在这个场景下,你希望通过Express.js来处理从URL传递的多个参数,以便能够删除特定博客文章下的评论。以下是一个简单的解决方案,包括如何在URL中传递两个参数以及如何使用这些参数来实现你的需求。

示例代码

首先,确保你已经安装了必要的库:

npm install express mongoose

接下来,创建一个基本的Express应用,并定义路由来处理删除操作:

const express = require('express');
const mongoose = require('mongoose');

// 连接到MongoDB数据库
mongoose.connect('mongodb://localhost:27017/blog', { useNewUrlParser: true, useUnifiedTopology: true });

// 定义Schema
const commentSchema = new mongoose.Schema({
    text: String,
    createdAt: { type: Date, default: Date.now }
});

const Comment = mongoose.model('Comment', commentSchema);

const app = express();

// 删除评论的路由
app.delete('/articles/:articleId/comments/:commentId', async (req, res) => {
    try {
        // 从请求中获取参数
        const articleId = req.params.articleId;
        const commentId = req.params.commentId;

        // 查找并删除评论
        await Comment.findByIdAndDelete(commentId);
        
        res.status(200).send('Comment deleted successfully');
    } catch (error) {
        res.status(500).send('Error deleting comment');
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

解释

  1. 连接到数据库:我们使用mongoose.connect()来连接到MongoDB数据库。
  2. 定义Schema:定义了一个简单的Comment模型,包含文本和创建日期。
  3. 创建路由:定义了一个DELETE路由/articles/:articleId/comments/:commentId,它接受两个参数:articleIdcommentId
  4. 获取参数:使用req.params来获取URL中的参数。
  5. 删除评论:使用Comment.findByIdAndDelete(commentId)来删除指定ID的评论。
  6. 错误处理:如果删除过程中出现任何问题,则返回500状态码。

这样,当你发送一个DELETE请求到/articles/{articleId}/comments/{commentId}时,就会删除与给定commentId关联的评论。希望这能解决你的疑问!


?id1=&id2=

posts/:post_id/comments/:id

这样直接写也可以是么

原来这样

在Express中,你可以通过多种方式传递多个参数来处理复杂的路由。你可以使用查询参数、路径参数或者请求体中的参数。针对你的需求(删除某个文章下的特定评论),最佳实践是通过路径参数来传递两个ID:一个是文章ID,另一个是评论ID。

示例代码

假设你有一个文章模型 Article 和一个评论模型 Comment,并且你希望删除文章下特定的评论。

路由定义

首先,你需要在Express应用中定义一个路由来接收这两个参数:

const express = require('express');
const app = express();
const mongoose = require('mongoose');

// 假设你已经定义了Article和Comment模型
const Article = mongoose.model('Article', new mongoose.Schema({}));
const Comment = mongoose.model('Comment', new mongoose.Schema({}));

app.delete('/articles/:articleId/comments/:commentId', async (req, res) => {
    try {
        const { articleId, commentId } = req.params;
        
        // 查找指定的文章
        const article = await Article.findById(articleId);
        if (!article) return res.status(404).send('Article not found.');

        // 查找并删除指定评论
        const removedComment = await Comment.findByIdAndRemove(commentId);
        if (!removedComment) return res.status(404).send('Comment not found.');

        // 可选: 更新文章中的评论列表(如果需要)
        article.comments.pull(commentId);
        await article.save();

        res.send('Comment successfully removed.');
    } catch (err) {
        res.status(500).send('Server error.');
    }
});

// 运行服务器
app.listen(3000, () => console.log('Server running on port 3000'));

解释

  1. 路由定义app.delete('/articles/:articleId/comments/:commentId', ...) 定义了一个DELETE方法的路由,该路由接受两个路径参数 articleIdcommentId

  2. 获取参数req.params 获取路径参数。在这个例子中,req.params.articleIdreq.params.commentId 分别对应于要删除的评论所在的那篇文章的ID和要删除的评论的ID。

  3. 查找并删除:使用 findByIdAndRemove 方法从数据库中删除评论,并确保在删除之前找到了对应的文章和评论。如果找不到相应的文章或评论,则返回404错误。

  4. 可选更新:如果你的应用逻辑要求删除评论后更新文章的评论列表,可以使用 pull 方法从文章的评论数组中移除指定的评论ID,然后保存文章。

这种方法使路由清晰且易于维护,同时直接利用了Mongoose的API简化了操作流程。

回到顶部