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;

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值