Search code examples
javascriptmongodbmongoosemongodb-querymern

Mongoose update field if included in request object


I'm creating a form for users to update their profile, including their profile picture. If they have included a profile picture in the form they've submitted, then I want to update their profilePic field to the image link returned from AWS once that upload is complete. If they haven't included a profile pic, then leave the previous image link in the database as is. In either case, the remaining fields will be updated with whatever was submitted.

My MongoDB query:

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,

})

While this successfully changes the remaining fields, it does not change the profilePic field when a new profile picture is submitted. I have console logged the imageLink value and confirmed that it is in fact the new image link from the AWS S3 bucket.

Here is my user schema:

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
        }
    }
})

Any help is greatly appreciated!


Solution

  • No need to use $cond, you can just conditionally add the profilePic field in JavaScript:

    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);