0

This is my controller:

const updateUser = async (req, res) => {
        const uid = req.params.uid
        const updates = req.body
        console.log(updates)
        const status = await dao.updateUser(uid, updates)
        res.json(status)
    }

This is my dao:

export const updateUser = async (uid, userUpdates) => {
  await usersModel.updateOne({ _id: uid }),
      { $set: userUpdates }
}

This is what I sent in the json body (as the userUpdates):

{
    "username": "hihi",
    "password": "chloe123",
    "firstName": "chloe",
    "lastName": "hu",
    "email": "123456@gmail.com",
    "dob": "2022-12-05",
    "phone": "000-000-0000",
    "type": "STUDENT"
}

I searched this error, what I sent is an object, not a new model, so I confused why this error still happened, since if it is an object, it will not automatically create a _id, I am wondering how this should be solved. Thanks!

qwe123
  • 51
  • 1
  • 3
  • Can you clarify the error? Is calling updateUser actually falsely inserting a new user into the database? – justin Dec 08 '22 at 22:40
  • The error is that when I sent the json in the body to the updateUser controller, it gave me this error: Performing an update on the path '_id' would modify the immutable field '_id' – qwe123 Dec 08 '22 at 23:56
  • The `Model.update` method syntax is `Model.update( { someFld: someValue }, { updateObject } )` - Are you sure you are following this syntax? – prasad_ Dec 09 '22 at 01:18

1 Answers1

1

The DAO method uses updateOne incorrectly, you have placed the $set part outside updateOne. It is supposed to be,

export const updateUser = async (uid, userUpdates) =>  await usersModel.updateOne({_id: uid},{ $set: userUpdates })
turivishal
  • 34,368
  • 7
  • 36
  • 59