Mongoose更新字段(如果包含在请求对象中)

rwqw0loc  于 2023-02-16  发布在  Go
关注(0)|答案(1)|浏览(132)

我正在创建一个表单,供用户更新其个人资料,包括个人资料图片。如果他们在提交的表单中包含个人资料图片,则我希望在上传完成后将其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
        }
    }
})

任何帮助是非常感谢!

xurqigkl

xurqigkl1#

不需要使用$cond,您可以在JavaScript中有条件地添加profilePic字段:

const update = {
  username: req.body.username,
  email: req.body.email,
  shortDescription: req.body.shortDescription,
  fullDescription: req.body.fullDescription,
  paymentInfo: req.body.paymentInfo,
};

if (req.file) {
  update.profilePic = imageLink;
}

await User.findByIdAndUpdate(req.body._id, update);

相关问题