以音乐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" });
}
});
注意这里完整代码,一是唱片的模型数据结构文章来源:https://www.toymoban.com/news/detail-818019.html
// 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;
二是最新更改版代码文章来源地址https://www.toymoban.com/news/detail-818019.html
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;
到了这里,关于react后端开发:如何根据特定ID创建新的用户信息?的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!