[英]Using findOneAndUpdate with varying field values
我很好奇,是否有更好的方法來更新字段值。 我使用的字段值有時會出現,有時不會出現,這取決於用戶創建的帖子類型:
這是我的代碼,列出要添加到數據庫中的字段
switch (req.body.postType) {
case "text":
postFields = {
postType: "text",
postBody: req.body.postBody
};
break;
case "video":
postFields = {
postType: "video",
postTitle: req.body.postTitle,
postBody: req.body.postBody,
video: {
...req.files["postVideo"][0],
thumbnail: { ...req.files["postVideoThumbnail"][0] }
}
};
break;
case "photo":
postFields = {
postType: "photo",
postTitle: req.body.postTitle,
postBody: req.body.postBody,
photo: {
...req.files["postPhoto"][0]
}
};
break;
case "document":
postFields = {
postType: "document",
postTitle: req.body.postTitle,
postBody: req.body.postBody,
document: {
...req.files["postDocument"][0]
}
};
break;
default:
return res.status(400).json({
Error:
"Incorrect postType sent to server. Must be: text, video, photo"
});
}
構建findOneAndUpdate
這個之后,我可以按如下方式使用findOneAndUpdate
Feed.findOneAndUpdate(
{ school: req.user.school },
{
$push: {
posts: postFields
}
},
{ new: true }
)
有沒有更好的方法來創建字段值?
由於您已經在使用ES6,因此可以執行以下操作:
let { postType, postBody, postTitle } = req.body // <-- de-structure
let postFields = {
postType,
postBody,
postTitle, // <-- no title for text?
...(type === 'video' ? { video: {...req.files["postVideo"][0], thumbnail: { ...req.files["postVideoThumbnail"][0]}}} : {}),
...(type === 'photo' ? { photo: { ...req.files["postPhoto"][0]}} : {}),
...(type === 'document' ? { document: {...req.files["postDocument"][0]}} : {}),
}
如果text
沒有標題,則僅使用與video
等相同的方法,在video
中使用三元運算符 ;如果類型為text
,則通過散布帶有標題的對象來添加標題...
基本上,該想法是使用帶有三元運算符的傳播來有條件地用屬性裝飾對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.