Express + MongoDB 实现视频点播

一、安装依赖

npm install multer

二、编写代码

1. 定义视频模型

const mongoose = require("mongoose");
const videoSchema = new mongoose.Schema({
  title: { type: String, required: true },
  description: { type: String },
  filePath: { type: String, required: true },
  thumbnailPath: { type: String },
  uploadDate: { type: Date, default: Date.now },
});
module.exports = mongoose.model("Video", videoSchema);

2. 配置 Express 服务器和 MongoDB 连接

// 配置 multer 用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  },
});
const upload = multer({ storage: storage });
// 静态文件服务,用于访问视频文件
app.use("/public", express.static(path.join(__dirname, "public")));
// 处理视频上传
app.post("/upload", upload.single("video"), async (req, res) => {
  try {
    const { title, description } = req.body;
    const filePath = `/public/videos/${req.file.filename}`;
    const newVideo = new Video({
      title,
      description,
      filePath,
    });
    await newVideo.save();
    res.status(200).json({ message: "视频上传成功", video: newVideo });
  } catch (error) {
    res.status(500).json({ message: "视频上传失败", error: error.message });
  }
});
// 获取视频列表
app.get("/videos", async (req, res) => {
  try {
    const videos = await Video.find();
    res.status(200).json(videos);
  } catch (error) {
    res.status(500).json({ message: "获取视频列表失败", error: error.message });
  }
});
// 播放视频
app.get("/videos/:id", async (req, res) => {
  try {
    const video = await Video.findById(req.params.id);
    if (!video) {
      return res.status(404).json({ message: "视频未找到" });
    }
    res.sendFile(path.join(__dirname, video.filePath));
  } catch (error) {
    res.status(500).json({ message: "播放视频失败", error: error.message });
  }
});

你可能感兴趣的:(express,mongodb,数据库)