You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于路由变量从MongoDB获取闪卡应用数据?

闪卡应用从MongoDB获取数据的完整实现方案

刚好我之前做过类似的闪卡应用改造,给你一套适配需求的落地方案——假设你用的是Node.js + Express(毕竟你的路由是localhost:5000开头的),一步步来:

1. 安装必要依赖

先确保你已经初始化了Node项目,然后安装Express(处理路由)和Mongoose(操作MongoDB):

npm install express mongoose

2. 连接本地MongoDB数据库

创建一个db.js文件(或者直接写在主服务文件里),负责数据库连接:

const mongoose = require('mongoose');

async function connectDB() {
  try {
    await mongoose.connect('mongodb://localhost:27017/flashcards', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('✅ MongoDB连接成功!');
  } catch (err) {
    console.error('❌ MongoDB连接失败:', err);
    process.exit(1);
  }
}

module.exports = connectDB;

3. 定义卡片的Schema与模型

创建models/Card.js文件,映射你cards集合的结构:

const mongoose = require('mongoose');

// 完全匹配你集合中文档的字段:question、hint、answer
const cardSchema = new mongoose.Schema({
  question: {
    type: String,
    required: true
  },
  hint: {
    type: String,
    required: true
  },
  answer: {
    type: String,
    required: true
  }
});

// Mongoose会自动将模型名转为小写复数,所以`Card`模型正好对应你的`cards`集合
module.exports = mongoose.model('Card', cardSchema);

4. 编写路由处理逻辑

在主服务文件(比如server.js)里,实现你需要的路由逻辑:

const express = require('express');
const connectDB = require('./db');
const Card = require('./models/Card');

const app = express();
const PORT = 5000;

// 先连接数据库再启动服务
connectDB().then(() => {
  app.listen(PORT, () => {
    console.log(`🚀 服务器运行在http://localhost:${PORT}`);
  });
});

// 处理你的闪卡路由:localhost:5000/${id}?side=${question/answer}
app.get('/:id', async (req, res) => {
  try {
    const { id } = req.params; // 提取URL中的卡片ID
    const { side } = req.query; // 提取查询参数中的side值

    // 先验证side参数是否合法
    if (!['question', 'answer'].includes(side)) {
      return res.status(400).json({ error: 'side参数只能是question或answer' });
    }

    // 根据ID查询对应卡片
    const card = await Card.findById(id);
    if (!card) {
      return res.status(404).json({ error: '未找到对应的闪卡' });
    }

    // 返回对应内容,同时带上提示方便前端使用
    res.json({
      cardId: card._id,
      content: card[side],
      hint: card.hint
    });
  } catch (err) {
    console.error('请求处理失败:', err);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

5. 测试与验证

启动服务器:

node server.js

然后用浏览器/Postman测试路由:

  • 获取问题:http://localhost:5000/[你的卡片ID]?side=question
  • 获取答案:http://localhost:5000/[你的卡片ID]?side=answer

如果不知道卡片ID,可以临时加一个获取所有卡片的路由:

app.get('/cards', async (req, res) => {
  try {
    const allCards = await Card.find();
    res.json(allCards);
  } catch (err) {
    res.status(500).json({ error: '获取卡片列表失败' });
  }
});

访问http://localhost:5000/cards就能看到所有卡片的完整信息(包括ID)了。

内容的提问来源于stack exchange,提问作者veryspry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:07:56