How to update one field from a passed object in mongoose

Viewed 806

Incase I have an object that looks like the one below

const auth = {
        geohash: args.input.geohash,
        offenses: args.input.offenses,
        online: args.input.online,
        paid: args.input.paid,
        profilePic: args.input.profilePic,
        username: args.input.username,
    }

and I pass it inorder to update a document

const update = { _id: mongoose.Types.ObjectId(args._id) }
    const value = await DiscoverUsers.findOneAndUpdate(update, auth, { useFindAndModify: false, new: true })

so incase I only want to update the username and I don't want to keep creating a mutation for updating each field in the document. lets say my mutation looks like this

 mutation{
  updateDiscoverUsers(_id:"5dab7c198a83f235c89a964a",input:{username:"peter"}){
    username
  }
}

but this only updates the username but it makes the rest of the fields null but I only want to find a way to only update the fields I have passed in the mutation and the rest remain the same. so I can update the username and profilePic only and the rest remain unchanged. I would be grateful for the help and thanks in advance

1 Answers

You should use the atomic operator $set to update only where you want, and you should pass only the fields you want to update, not all of them otherwise all the fields are going to be updated by the new value.

like:

const value = await DiscoverUsers.findOneAndUpdate(update, {$set:{username:"pedro"}}, { useFindAndModify: false, new: true })
Related