You will notice a key new set to true, that is used, so the query will return the updated new document. Then we are using findOneAndUpdate method of mongoose which will find the particular record in our case matching with the username we are providing then updates the nickname with new nickname. New nickname also we will get in request body. Here we are creating a PUT endpoint which will receive username against which we have to update the nickname. Only difference is that we use find to get one or more records matching the condition.Ĭonst result = await User.findOneAndUpdate( We can use find as well instead of findOne, it will give the same result. You will notice we are using findOne method, which as the name suggests will fetch only one record, also we have a unique constraint on username which means we will only have a single record for every username in database. In case of any other error, we are doing the same as we did above. ![]() If user is not found we are sending 404 back in response with a message. First we are retrieving the username from request parameter then using a findOne method of mongoose to retrieve the record associated with it from database and passing it back as response. Here we have created a ‘/read/:username’ GET endpoint, where we are passing the username to find the record associated with it. const express = require('express') Īpp.use(express.urlencoded( does not exist`) ![]() The app.js file will contain the following code. Now let’s create app.js file in our main folder which will be the entry point to the NodeJS application. Npm i express body-parser mongoose dotenv nodemon nodemon, which helps us run the NodeJS application without having to restart it every time we save any changes to our code.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |