我想為我的專案做一個更新方法,但我無法解決這個問題。我的模型有一個現場呼叫蛞蝓。如果需要,我添加資料以使該值唯一。但是,我findByIdAndUpdate在我的更新功能上使用方法。我想知道有沒有辦法在更新這個模型之前獲取資料?我是否必須向我的資料庫發出至少 2 個不同的請求才能獲取舊資料,或者我使用的這種方法是否讓我有機會比較資料?因為如果標題欄位發生了變化,我需要比較它并生成新的 slug 值。
類別型號
const mongoose = require('mongoose')
const CategorySchema = mongoose.Schema({
title: {
type: String,
required: true,
trim: true,
minLength: 3,
maxLength: 70
},
description: {
type: String,
requried: true,
trim: true,
minLength: 30
},
coverImage: {
type: String,
trim: true
},
slug: {
type: String,
unique: true,
required: true
}
}, {collection: "categories", timestamps: true})
module.exports = mongoose.model('category', CategorySchema);
更新功能
const update = async (req, res, next) => {
delete req.body.createdAt;
delete req.body.updatedAt;
try {
const data = req.body;
data.coverImage = req.file ? req.file.path.replace(/\\/g, "/") : undefined;
data.slug = data.title ? slugCreator(data.title, null): undefined;
const result = await CategoryModel.findByIdAndUpdate(req.params.categoryId, data, { new: true, runValidators: true });
if (result) {
return res.json({
message: "Category has been updated",
data: result
});
}else{
throw createError(404, "Category not found.")
}
} catch (error) {
next(createError(error));
}
};
uj5u.com熱心網友回復:
您可以首先通過獲取檔案來解決您的問題,然后使用 save 方法進行更新,如下例所示
const update = async (req, res, next) => {
delete req.body.createdAt;
delete req.body.updatedAt;
try {
const data = req.body;
//here you have the current category
const category = await CategoryModel.findById(req.params.categoryId);
if (!category) {
throw createError(404, 'Category not found.');
}
//do all you comparation and setting the data to the model...
category.slug = data.title ? slugCreator(data.title, null) : undefined;
category.coverImage = req.file
? req.file.path.replace(/\\/g, '/')
: undefined;
await category.save();
return res.json({
message: 'Category has been updated',
data: category,
});
} catch (error) {
next(createError(error));
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473945.html
