0% found this document useful (0 votes)
71 views12 pages

WDFP Practical Ques

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

WDFP Practical Ques

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

1. i) Write a node.

js program for the following


a) Display a message in the browser
b) Display the current date and time in the browser
c) Pass a query string in URL

const http = require('http');


const url = require('url');

const server = http.createServer((req, res) => {


res.writeHead(200, {'Content-Type': 'text/html'});

// a) Display a message in the browser


res.write('<h1>Hello, World!</h1>');

// b) Display the current date and time in the browser


const currentDate = new Date();
res.write(`<p>Current Date and Time: ${currentDate.toLocaleString()}</p>`);

// c) Pass a query string in URL


const queryObject = url.parse(req.url, true).query;
if (queryObject.name) {
res.write(`<p>Hello, ${queryObject.name}!</p>`);
}

res.end();
});

server.listen(3000, () => {
console.log('Server listening on port 3000');
});

ii) Write a mongoDB command to insert multiple documents into the


students collection.

db.students.insertMany([
{ name: "Alice", age: 25, grade: "A" },
{ name: "Bob", age: 22, grade: "B" },
{ name: "Charlie", age: 23, grade: "C" }
]);

2. i) Write a node.js program for the following


a) Splits up a web address into readable parts
b) Display customized error message
const url = require('url');

const server = http.createServer((req, res) => {


// a) Splits up a web address into readable parts
const parsedUrl = url.parse(req.url, true);
const protocol = parsedUrl.protocol;
const hostname = parsedUrl.hostname;
const pathname = parsedUrl.pathname;
const query = parsedUrl.query;

console.log('Protocol:', protocol);
console.log('Hostname:', hostname);
console.log('Pathname:', pathname);
console.log('Query:', query);

// b) Display customized error message


if (req.url === '/error') {
res.writeHead(404, {'Content-Type': 'text/html'});
res.write('<h1>Page Not Found</h1>');
res.write('<p>The requested page could not be found.</p>');
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Hello, World!</h1>');
res.end();
}
});

server.listen(3000, () => {
console.log('Server listening on port 3000');
});

ii) Write mongoDB commands for the following


a) How do you find a document where the name is "John" in the users
collection?

db.users.findOne({ name: "John" });

b) How would you find all documents in the products collection where
the price is greater than 100?

db.products.find({ price: { $gt: 100 } });


3. i) Write a node.js program for the following
a) Fileupload operation
b) Event handling

const http = require('http');


const formidable = require('formidable');

const server = http.createServer((req, res) => {


if (req.url === '/upload' && req.method === 'POST') {
const form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
if (err) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Error parsing form: ' + err);
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('File uploaded successfully: ' + files.file.name);
}
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="/upload" method="post" enctype="multipart/form-
data">');
res.write('<input type="file" name="file"><br>');
res.write('<input type="submit" value="Upload">');
res.write('</form>');
res.end();
}
});

server.listen(3000, () => {
console.log('Server listening on port 3000');
});

ii) Write mongoDB commands for the following


a) Update the age of a student named "Alice" to 25 in the students
collection

db.students.updateOne({ name: "Alice" }, { $set: { age: 25 } });

b) update the status field to "active" for all documents in the employees
collection

db.employees.updateMany({}, { $set: { status: "active" } });


4. i) Write an Express.js program for the following
a) Implementation of 2 middlewares
b) Filtering paths using URL prefix

const express = require('express');


const app = express();

// Middleware 1: Log requests to the console


app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});

// Middleware 2: Add a custom header to the response


app.use((req, res, next) => {
res.setHeader('X-Powered-By', 'My Custom App');
next();
});

// Filter paths using URL prefix "/api"


app.use('/api', checkAuth);

// This route will be affected by both middlewares since it starts with '/api'
app.get('/api/data', (req, res) => {
res.send('Accessing protected API data with auth parameter!');
});

// This route is public and will only go through the logging middleware
app.get('/public', (req, res) => {
res.send('Accessing public data, no auth required.');
});

// A catch-all route to handle all other paths


app.get('*', (req, res) => {
res.send('404 - Page not found');
});

// Start the server


app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});

ii) Write mongoDB commands for the following


a) How do you delete a single document where the email is
"[email protected]" in the contacts collection?

db.contacts.deleteOne({ email: "[email protected]" });

b) Write a MongoDB command to delete all documents in the orders


collection where status is "canceled".

db.orders.deleteMany({ status: "canceled" });

5. i) Write an Express.js program for the following


a) Setting the status code
b) Parsing data from request

const express = require('express');


const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());

// a) Setting the status code


app.get('/status', (req, res) => {
res.status(200).send('Success');
});

app.get('/error', (req, res) => {


res.status(404).send('Not Found');
});

// b) Parsing data from request


app.post('/data', (req, res) => {
const data = req.body;
console.log(data);
res.send('Data received successfully');
});

app.listen(3000, () => {
console.log('Server listening on port 3000');
});

ii) Write mongoDB commands for the following


a) Write a query to find all documents in the students collection where
age is between 18 and 25.
db.students.find({ age: { $gte: 18, $lte: 25 } });

b) Write a MongoDB query to find all documents in the books collection


that contain the word "MongoDB" in the title field.

db.books.find({ title: /MongoDB/ });

RES OBJECT

6. i) Write an Express.js program for the following


a) Setting the status code
b) Parsing data from request
ii) Write mongoDB commands for the following
a) Update the age of a student named "Alice" to 25 in the students collection
b) update the status field to "active" for all documents in the employees
collection

7. i) Write an Express.js program for the following


a) Implementation of 2 middlewares
b) Filtering paths using URL prefix
ii) Write mongoDB commands for the following
a) Update the age of a student named "Alice" to 25 in the students collection
b) update the status field to "active" for all documents in the employees
collection
8. i) Write a node.js program for the following
a) Fileupload operation
b) Event handling
ii) Write mongoDB commands for the following
a) Write a query to find all documents in the students collection where age is
between 18 and 25.
b) Write a MongoDB query to find all documents in the books collection
that contain the word "MongoDB" in the title field.

9. i) Write a node.js program for the following


a) Splits up a web address into readable parts
b) Display customized error message

ii) Write mongoDB commands for the following


a) Write a MongoDB command to find the first 5 students sorted by age
in descending order.

db.students.find().sort({ age: -1 }).limit(5);

b) Write a MongoDB query to find all documents in the books


collection that contain the word "MongoDB" in the title field.
c)
db.books.find({ title: /MongoDB/i });

10. i) Write a node.js program for the following


a) Display a message in the browser
b) Display the current date and time in the browser
c) Pass a query string in URL

ii) Write mongoDB commands for the following


a) How do you update the email of a specific user in the customers
collection where the customerID is 12345?

db.customers.updateOne({ customerID: 12345 }, { $set: { email:


"[email protected]" } });

b) Write a MongoDB command to add a status field with the value


"inactive" to all documents in the users collection.?

db.users.updateMany({}, { $set: { status: "inactive" } });


1. i) Write an Express.js program for the following

a) Setting the status code


b) Parsing data from request

ii) Write mongoDB commands for the following


a) Write a command to insert a new employee record into the employees collection
with the following fields: name "John Doe", age 28, and department "HR".

db.employees.insertOne({ name: "John Doe", age: 28, department: "HR" });

b) Write a MongoDB command to insert multiple documents into the products


collection, each having fields productName, price, and category.

db.products.insertMany([
{ productName: "Product A", price: 19.99, category: "Electronics" },
{ productName: "Product B", price: 29.99, category: "Clothing" },
{ productName: "Product C", price: 9.99, category: "Books" }
]);

2. i) Write an Express.js program for the following


a) Implementation of 2 middlewares
b) Filtering paths using URL prefix

ii) Write mongoDB commands for the following


a) How do you find all documents in the users collection where the age is greater
than 25?

db.users.find({ age: { $gt: 25 } });

c) Write a command to find a document in the customers collection where the


customerID is 1001 and only return the name and email fields.

db.customers.findOne({ customerID: 1001 }, { projection: { name: 1, email: 1 } });

3. i) Write a node.js program for the following


a) Fileupload operation
b) Event handling

ii) Write mongoDB commands for the following


a) Write a MongoDB query to retrieve all products in the inventory collection where
quantity is between 10 and 100, inclusive.

db.inventory.find({ quantity: { $gte: 10, $lte: 100 } });

b) Write a command to update the price of a product where the productName is "Laptop"
to 1200 in the products collection.

db.products.updateOne({ productName: "Laptop" }, { $set: { price: 1200 } });

4. i) Write a node.js program for the following


a) Splits up a web address into readable parts
b) Display customized error message

ii) Write mongoDB commands for the following


a) How do you update the status of all orders in the orders collection where the
status is "pending" to "shipped"?
db.orders.updateMany({ status: "pending" }, { $set: { status: "shipped" } });

b) Write a command to increment the quantitySold field by 5 for all documents in


the sales collection where productID is 2001.

db.sales.updateMany({ productID: 2001 }, { $inc: { quantitySold: 5 } });


.
5. i) Write a node.js program for the following
a) Display a message in the browser
b) Display the current date and time in the browser
c) Pass a query string in URL

ii) Write mongoDB commands for the following


a) Write a command to delete a single document from the employees collection
where the employeeID is 101.

db.employees.deleteOne({ employeeID: 101 });

b) Write a MongoDB command to delete all documents from the products collection
where the category is "obsolete".

db.products.deleteMany({ category: "obsolete" });

6. i) Write a node.js program for the following


a) Display a message in the browser
b) Display the current date and time in the browser
c) Pass a query string in URL

ii) Write mongoDB commands for the following


a) How do you delete all documents from the logs collection?

db.logs.deleteMany({});

b) Write a command to remove a document from the orders collection where the
orderID is 555, if it exists.

db.orders.deleteOne({ orderID: 555 });

7. i) Write a node.js program for the following


a) Splits up a web address into readable parts
b) Display customized error message

ii) Write mongoDB commands for the following


a) Write a query to retrieve the first 5 documents in the students collection, sorted
by age in descending order.

db.students.find().sort({ age: -1 }).limit(5);

b) Update the status field to "closed" and add a closingDate field for all documents
in the projects collection where dueDate is less than the current date.

db.projects.updateMany(
{ dueDate: { $lt: new Date() } },
{ $set: { status: "closed", closingDate: new Date() } }
);

8. i) Write a node.js program for the following


a) Fileupload operation
b) Event handling

ii) Write mongoDB commands for the following


a) Write a MongoDB query to update a product's quantity by 10, and then delete
the product if its quantity becomes greater than 1000.

db.products.updateOne(
{ productName: "YourProductName" },
{
$inc: { quantity: 10 },
$cond: {
if: { $gt: ["$quantity", 1000] },
then: { $remove: true },
else: {}
}
}
);

9. i) Write an Express.js program for the following


a) Implementation of 2 middlewares
b) Filtering paths using URL prefix

ii) Write mongoDB commands for the following


a) Insert a document into the students collection with the fields name, age, grade,
and subjects where subjects is an array containing "Math" and "Science".

db.students.insertOne({
name: "Alice",
age: 20,
grade: "A",
subjects: ["Math", "Science"]
});

b) Insert multiple documents into the orders collection with fields orderID,
product, quantity, and status.
db.orders.insertMany([
{ orderID: 1001, product: "Laptop", quantity: 2, status: "Pending" },
{ orderID: 1002, product: "Smartphone", quantity: 1, status: "Shipped" },
{ orderID: 1003, product: "Book", quantity: 3, status: "Cancelled" }
]);

10. i) Write an Express.js program for the following


a) Setting the status code
b) Parsing data from request

ii) Write mongoDB commands for the following


a) Find all documents in the employees collection where department is "IT" and
age is less than 40.

db.employees.find({ department: "IT", age: { $lt: 40 } });


b) Write a query to return only the name and salary of employees in the employees
collection where the salary is greater than 5000.

db.employees.find({ salary: { $gt: 5000 } }, { projection: { name: 1, salary: 1 } });

You might also like