0% found this document useful (0 votes)
11 views4 pages

NodeJS DAY 5

this is node.js day 5 notes

Uploaded by

aditipandey1114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

NodeJS DAY 5

this is node.js day 5 notes

Uploaded by

aditipandey1114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

DAY 5

WHAT IS MODELS & SCHEMA?

 Models are like blueprint of our database.


 It’s a representation of a specific collection in MongoDB, Like a person
 Once u have defined a model, u can create, read, update and delete
document in the corresponding MongoDB collection.
 Mongoose allows u to define a schema for your documents. A schema is
like blueprint that defines the structure & data types of your documents
within a collection.
 Each person’s detail (like chef, owner, manager, waiter).

{
"name": "Alice",
"age": 28,
"work":" chef",
"mobile": "123-456-7890",
"email":" [email protected]",
"address": "123 Main St, City",
"salary":60000
}

 Parameters
 Type, requires, unique, etc.
WHAT IS body-parser
 Body Parser is a middleware library for Express.js
 It is used to parser & extract the body of incoming HTTP requests.
 When a client (e.g., a web browser or a mobile app) sends data to a
server, it typically includes that data in the body of an HTTP request.
 This data can be in various formats, such as JSON, form, data, or URL-
encoded data. Body Parser helps parse & extract this data form the
request! So that you can work with it in your Express.js application.
 Body Parser processes the request body before it reaches your route
handlers, making the parsed data available in the req. body for further
processing.
 bodyParser.json() automatically parser the JSON data from the request
body and converts it into a JavaScript object, which is then stored in the
req. body

 Express.js uses lots of middleware and to use middleware we use the


app.use()
const bodyParser = require('body-parser');
app.use(bodyParser.json());

 Send Data from Client to Server

 We need an Endpoint where the client sends data and data needs to be
saved in the database

 We need a method called POST


 Now code the POST method to add the person
 If we send the random values as well Mongoose will not save random
values other than predefined schema

newPerson.save((error, savedPerson)=>{
if(error){
console.error('Error is saving person: ',error);
res.status(500).json({error: 'internal server error'});
}else{
console.log('Data saved');
res.status(201).json(savedPerson);
}
});

 Async and Await

 Nowadays no one uses callback functions like, we used in the POST


methods. They look quit complex & also do not give us code readability.
 What actually callback does, callback is a function that is executed just
after the execution of another main function, it means the callback will
wait until its main function is not executed.
 Async and await are features in JavaScript that make it easier to work
with asynchronous code, such as network requests, file system
operations, or database queries.
 Using try and catch block.
 The try block contains the code for creating a new Person document and
saving it to the database using await newPerson.save().
 If an error occurs during any step, it is caught in the catch block, and an
error response is sent with a 500 Internal Server Error status

try{
const data = req.body //Assuming the request body contain the
person data

// Create a new Person document using the Mongoose model


const newPerson = new Person(data);

// Save the new person to the database


const response = await newPerson.save()
console.log('data saved');
res.status(200).json(response);
}catch(err){
console.log(err);
re.status(500).json({error: 'Internal Server Error'});
}

 Async Function (async):

 An async function is a function that is designed to work with


asynchronous operations. You declare a function as async by placing the
async keyword before the function declaration.
 The primary purpose of an async function is to allow you to use the
await keyword inside it, which simplifies working with promises and
asynchronous code.
 Inside an async function, you can use await to pause the execution of
the function until a promise is resolved. This makes the code appear
more synchronous and easier to read.

 Await (await):

 The await keyword is used inside an async function to wait for the
resolution of a promise. It can only be used within an async function.
 When await is used, the function pauses at that line until the promise is
resolved or rejected. This allows you to write code that appears
sequential, even though it’s performing asynchronous tasks.
 If the promise is resolved, the result of the promise is returned. If the
promise is rejected, it throws an error that can be caught using try…
catch.

 CRUD application

You might also like