gpt4 book ai didi

javascript - 将 findOneAndUpdate 与不同的字段值一起使用

转载 作者:行者123 更新时间:2023-12-02 23:33:56 24 4
gpt4 key购买 nike

我很想知道是否有更好的方法来更新字段值。我使用的字段值有时会存在,有时不会,具体取决于用户创建的帖子类型:

这是我的代码,用于列出要添加到数据库的字段

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,如下所示

 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没有标题,那么只需使用与使用ternary operatorvideo等相同的方法即可。如果类型是 text,只需通过传播带有标题的对象来添加标题...

基本上,这个想法是使用带有三元运算符的扩展来有条件地用属性修饰对象。

关于javascript - 将 findOneAndUpdate 与不同的字段值一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56367214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com