1
Either one should be possible.
Zooming out, let's think about why this is the case by thinking about what happens at a high level.
- A client sends an HTTP request to a server.
- The server receives the request.
- The server parses the request (eg. such that
req.method
is POST
).
- The server decides what code to execute (eg.
app.post('/foo/bar', handler)
).
- The server executes that code (eg.
handler()
).
Roughly. The big point here is that in step 4, it is the server that decides what to do. The request could be DELETE. It doesn't matter. The server can decide that when it sees a DELETE request, it's going to create a record. Now, that is probably a bad idea. My point is just that it is possible.
With that said, let's think about why it is only working with POST but not PUT. You'll have to look through your server code and check out how the routing is done (perhaps with Express?). There is going to be some routing logic that is looking for a POST request. You can change it to look for PUT instead if you would like.
To be clear, the answer will lie in your server's routing logic. It actually has nothing to do with Mongoose. Mongoose lives in step five of my outline above, whereas the answer to your question lives in step four.
2
Let's ask the question of whether it should be PUT, POST, or maybe something else.
- POST is for creating records.
- PUT is for replacing entire records.
- PATCH is another option available for updating a portion of an existing record.
So if you have a User record with a username
, email
and password
, if you are sending over { username: "johndoe", email: "johndoe@example.com", password: "020392" }
as the request payload and replacing the existing record with those values, then that would be a PUT request. But if you only want to change, let's say the email, then you could send something like { email: "johndoe@example.com" }
to the server and only update that email
field with Mongoose, and use a PATCH request for that. Check out Use of PUT vs PATCH methods in REST API real life scenarios for more information on PUT vs PATCH.