我正在创建一个表单,供用户更新其个人资料,包括个人资料图片。如果他们在提交的表单中包含个人资料图片,则我希望在上传完成后将其profilePic
字段更新为AWS返回的图像链接。如果他们未包含个人资料图片,则将数据库中以前的图像链接保留原样。无论哪种情况,其余字段将根据所提交的内容进行更新。
我的MongoDB查询:
let user = await User.findByIdAndUpdate(req.body._id, {
// if user submitted a profile pic (if there is a req.file) then update to the new image link
$cond: {
if: req.file,
then: {profilePic: imageLink}
},
// update the remaining fields regardless
username: req.body.username,
email: req.body.email,
shortDescription: req.body.shortDescription,
fullDescription: req.body.fullDescription,
paymentInfo: req.body.paymentInfo,
})
虽然这成功地更改了其余的字段,但在提交新的个人资料图片时,它不会更改profilePic字段。我已经控制台记录了imageLink
值,并确认它实际上是来自AWS S3存储桶的新图像链接。
下面是我的用户模式:
const userSchema = new Schema({
profilePic: {
type: String,
default: < link to default image on AWS >
},
username: {
type: String,
required: true
},
email: {
type: String,
unique: true,
trim: true,
lowercase: true,
required: true
},
password: {
type: String,
trim: true,
minLength: 8,
required: true
},
shortDescription: {
type: String,
trim: true,
maxLength: 70,
default: '',
},
fullDescription: {
type: String,
trim: true,
maxLength: 4000,
default: '',
},
paymentInfo: {type: String},
publisherAgreement: {
type: Boolean,
default: false
},
subscriptions: [{
publisherId: {
type: mongoose.Schema.Types.ObjectId,
},
}],
}, {
timestamps: true,
toJSON: {
transform: function(doc, ret) {
delete ret.password
return ret
}
}
})
任何帮助是非常感谢!
1条答案
按热度按时间xurqigkl1#
不需要使用
$cond
,您可以在JavaScript中有条件地添加profilePic
字段: