How to delete specific fields in a mongoDb via mongoose

I’m trying to delete only specific fields in my mongoDb user document but i don’t think using the userModel.deleteOne({_id:id}) would not suffice as this would delete the entire document which isn’t what i want. UserModel.updateOne({_id:id},{$unset:{email: 1, firstName: 1}}); doesn’t seem to work either .

        "_id": "12345678" ,
        "dob": null,
        "createdAt":  "2021-09-16T09:11:55.199Z" ,
        "email": "",
        "firstName": "iam1234",
        "lastName": "test14",
        "webisite": "",
        "uid": "SKkZZ3a",
        "skills": []

in this context, I want to delete firstName, lastName email website skills dob . Leaving me with just _id and uid.

Your updateOne() works well with the shell.

If mongoose stops you from doing it, (Editorial comment: another pitfall of using an abstraction layer) then I would check the schema of UserModel. May be it prevents you for non existing values. If this is the case then modify the schema to allow what you want to do or try using $set with null.

Hi @steevej i don’t quite follow. could you please be a little more specific?

I do not think I can but I will try.

MongoDB works like you wish because the deleteOne() you posted works correctly.

You are using mongoose and you cannot do it. So mongoose is the problem. So you change the mongoose schema to support what you want or you alter what you want by setting null values.