react后端开发:如何根据特定ID创建新的用户信息?

以音乐app开发为例,我们想要在想要创建新的唱片库,就需要使用Post连接服务器端新建唱片ID,并在该ID处插入唱片信息。怎么做呢?

使用create同时创建id和唱片信息

existingAlbum = await Album.create({ _id: albumId, ...albumData });

不过在这之前,我们一般先需要进行判断,新写入的唱片是否存在,比如某用户已经上传了周杰伦的青花瓷,而另一名用户又再次上传了同一首歌,我们就不会让该用户上传这首歌,并在他的页面进行报错。这里为了简单我们用的是ID进行判断(实际上需要判断,歌手名和歌曲名,用find)

const express = require('express');
const router = express.Router();
const Album = require("./../models/album.model");

// POST /albums/:albumId/add
router.post("/albums/:albumId/add", async (req, res) => {
  const { albumId } = req.params;
  const albumData = req.body;

  try {
    // Try to find the album by ID
    let existingAlbum = await Album.findById(albumId);

    if (!existingAlbum) {
      // If album not found, you may choose to create a new one
      existingAlbum = await Album.create({ _id: albumId, ...albumData });
    } else {
      // If album found, update its data
      existingAlbum.set(albumData);
      await existingAlbum.save();
    }

    res.status(201).json({ message: "Album added/updated", existingAlbum });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

注意这里完整代码,一是唱片的模型数据结构

// CREATE MODEL: Album
const { Schema, model } = require("mongoose");

const albumSchema = new Schema({
  performer: { type: String }, 
  title: { type: String },
  cost: { type: Number }
});

const Album = model("Album", albumSchema);
// REMEMBER TO EXPORT YOUR MODEL:
module.exports = Album;

二是最新更改版代码

const express = require('express');
const router = express.Router();
const Album = require("./../models/album.model");

// POST /albums
router.post("/albums", async (req, res) => {
  const { singerName, songName, cost } = req.body;

  try {
    // Check if an album with the same singer name and song name already exists
    const existingAlbum = await Album.findOne({ singerName, songName });

    if (existingAlbum) {
      // If an album with the same singer name and song name exists, return an error response
      return res.status(400).json({ error: "Album with the same singer name and song name already exists" });
    }

    // If no existing album is found, create a new album
    const newAlbum = await Album.create({ singerName, songName, cost });
    res.status(201).json({ message: "Album created successfully", album: newAlbum });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

module.exports = router;