Practical Guide to Node.js, MongoDB, AngularJS and Flutter Projects
Practical 1: Node.js, Express and Mongoose Setup
Run these commands first:
npm init -ynpm install express mongoose cors dotenvmkdir models- Create the files:
app.js,db.js,models/Post.js,models/User.js
User.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, required: true }
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);Post.js
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
title: { type: String, required: true },
content: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, ref: "User" }
},
{ timestamps: true }
);
module.exports = mongoose.model("Post", PostSchema);db.js
const mongoose = require("mongoose");
const connectDB = async () => {
try {
await mongoose.connect("mongodb://127.0.0.1:27017/myDatabase", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB Connected...");
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;app.js
const mongoose = require("mongoose");
const connectDB = require("./db");
const User = require("./models/User");
const Post = require("./models/Post");
(async function main() {
await connectDB(); // Connect to MongoDB
try {
// Create a User
const user = await User.create({
name: "John Doe",
email: "[email protected]",
age: 25
});
console.log("User Created:", user);
// Create a Post linked to the User
const post = await Post.create({
title: "My 1st Post",
content: "This is a blog post",
author: user._id
});
console.log("Post Created:", post);
} catch (err) {
console.error("Error:", err);
} finally {
mongoose.connection.close(); // Close database connection
}
})();Practical 2: CRUD Operations with the MongoDB Native Driver
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
const dbName = "test_database";
const collectionName = "test_collection";
async function run() {
try {
await client.connect();
console.log("Connected to MongoDB");
const db = client.db(dbName);
const collection = db.collection(collectionName);
// Create Document
const createDocument = async (data) => {
const result = await collection.insertOne(data);
console.log("Document Inserted:", result.insertedId);
};
// Read Documents
const readDocuments = async (query = {}) => {
const documents = await collection.find(query).toArray();
console.log("Documents Found:", documents);
};
// Update Document
const updateDocument = async (filter, update) => {
const result = await collection.updateOne(filter, { $set: update });
console.log(`${result.matchedCount} Document(s) Matched, ${result.modifiedCount} Updated`);
};
// Delete Document
const deleteDocument = async (filter) => {
const result = await collection.deleteOne(filter);
console.log(`${result.deletedCount} Document(s) Deleted`);
};
// Perform CRUD Operations
await createDocument({ name: "Alice", age: 25 });
await createDocument({ name: "Bob", age: 30 });
await readDocuments();
await updateDocument({ name: "Alice" }, { age: 26 });
await readDocuments();
await deleteDocument({ name: "Bob" });
await readDocuments();
} finally {
await client.close();
console.log("Connection Closed.");
}
}
run().catch(console.dir);Run using the command: node app.js
Practical 3: AngularJS Form Validation
<title>AngularJS Form Validation Example</title>
<style>
.error {
color: red;
}
</style>
<h1>AngularJS Form Validation</h1>
<form name="user_form" ng-submit="submit_form()" novalidate>
<label>Username:</label>
<input type="text" name="username" ng-model="user.username" ng-minlength="3" required />
<span class="error" ng-show="user_form.username.$dirty && user_form.username.$error.required">*Required</span>
<span class="error" ng-show="user_form.username.$dirty && user_form.username.$error.minlength">*Must be at least 3 characters</span>
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required />
<span class="error" ng-show="user_form.email.$dirty && user_form.email.$error.required">*Required</span>
<span class="error" ng-show="user_form.email.$dirty && user_form.email.$error.email">*Invalid email format</span>
<label>Password:</label>
<input type="password" name="password" ng-model="user.password" required />
<span class="error" ng-show="user_form.password.$dirty && user_form.password.$error.required">*Required</span>
<button type="submit" ng-disabled="user_form.$invalid">Submit</button>
</form>
<p>{{msg}}</p>
<script>
var app = angular.module("validationApp", []);
app.controller("formController", function($scope) {
$scope.user = {};
$scope.submit_form = function() {
if ($scope.user_form.$valid) {
$scope.msg = "Form Submitted Successfully!";
} else {
$scope.msg = "Please correct errors before submitting.";
}
};
});
</script>Practical 4: AngularJS Modules and Controllers
<title>AngularJS Modules & Controllers</title>
<h1>{{title}}</h1>
<p>{{description}}</p>
<script>
// 1) Define a Module
var app = angular.module("myApp", []);
// 2) Define a Controller
app.controller("myController", function($scope) {
$scope.title = "Welcome to My AngularJS App";
$scope.description = "This is a simple example of Modules & Controllers.";
});
</script>Practical 5: AngularJS Error Handling
<title>AngularJS Error Handling</title>
<h1>Error Handling with $http</h1>
<button ng-click="getData()">Fetch Data</button>
<p>Error: {{errorMessage}}</p>
<p ng-show="data">Data: {{data}}</p>
<script>
var app = angular.module("errorApp", []);
app.controller("errorController", function($scope, $http) {
$scope.errorMessage = "";
$scope.data = "";
$scope.getData = function() {
$http.get("https://invalid-url-or-endpoint")
.then(function(response) {
// Success Callback
$scope.data = response.data;
})
.catch(function(error) {
// Error Callback
$scope.errorMessage = "Could not fetch data. " + error.statusText;
});
};
});
</script>Practical 6: Student Records Application
<title>Student Records App</title>
<h1>Student Records</h1>
<label>Name:</label>
<label>Age:</label>
<button type="submit">Add Student</button>
<th>Name</th>
<th>Age</th>
<th>Action</th>
<td>{{student.name}}</td>
<td>{{student.age}}</td>
<button ng-click="removeStudent($index)">Remove</button>
<script>
var app = angular.module("studentApp", []);
app.controller("studentController", function($scope) {
// Predefined List of Students
$scope.students = [
{ name: "Alice", age: 20 },
{ name: "Bob", age: 22 }
];
// Object to Hold New Student Data
$scope.newStudent = {};
// Add a New Student
$scope.addStudent = function() {
if ($scope.newStudent.name && $scope.newStudent.age) {
$scope.students.push({
name: $scope.newStudent.name,
age: $scope.newStudent.age
});
$scope.newStudent = {}; // Reset form
}
};
// Remove a Student by Index
$scope.removeStudent = function(index) {
$scope.students.splice(index, 1);
};
});
</script>Practical 8: AngularJS Hello World
First, create a folder named angular-hello-world and save an index.html file inside it.
<title>AngularJS Hello World</title>
<h1>Hello, {{name}}!</h1>
<p>Enter your name: <input type="text" ng-model="name"></p>
<p>Welcome, <strong>{{name}}</strong>! Have a great day.</p>
<script>
// Define an AngularJS Module
var app = angular.module("helloApp", []);
// Define a Controller
app.controller("HelloController", function($scope) {
$scope.name = "World"; // Default Value
});
</script>Practical 9: Flutter Firebase Authentication
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: AuthScreen(),
);
}
}
class AuthScreen extends StatefulWidget {
@override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
String msg = '';
Future<void> signUp() async {
try {
await _auth.createUserWithEmailAndPassword(
email: emailController.text,
password: passwordController.text,
);
setState(() {
msg = 'User Registered Successfully';
});
} catch (e) {
setState(() {
msg = e.toString();
});
}
}
Future<void> signIn() async {
try {
await _auth.signInWithEmailAndPassword(
email: emailController.text,
password: passwordController.text,
);
setState(() {
msg = 'User Logged In Successfully';
});
} catch (e) {
setState(() {
msg = e.toString();
});
}
}
Future<void> signOut() async {
await _auth.signOut();
setState(() {
msg = 'User Signed Out';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Flutter Auth")),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(controller: emailController, decoration: InputDecoration(labelText: 'Email')),
TextField(controller: passwordController, decoration: InputDecoration(labelText: 'Password'), obscureText: true),
SizedBox(height: 10),
ElevatedButton(onPressed: signUp, child: Text('Sign Up')),
ElevatedButton(onPressed: signIn, child: Text('Sign In')),
ElevatedButton(onPressed: signOut, child: Text('Sign Out')),
SizedBox(height: 10),
Text(msg, style: TextStyle(color: Colors.red)),
],
),
),
);
}
}Practical 10: Flutter Image Gallery
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: ImageGallery(),
);
}
}
class ImageGallery extends StatefulWidget {
@override
_ImageGalleryState createState() => _ImageGalleryState();
}
class _ImageGalleryState extends State<ImageGallery> {
final List<File> _images = [];
final ImagePicker _picker = ImagePicker();
Future<void> _pickImage() async {
final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
setState(() {
_images.add(File(pickedFile.path));
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Image Gallery")),
body: GridView.builder(
padding: EdgeInsets.all(10),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: _images.length,
itemBuilder: (context, index) {
return Image.file(_images[index], fit: BoxFit.cover);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _pickImage,
child: Icon(Icons.add_a_photo),
),
);
}
}Practical 11: Flutter Layouts
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LayoutDemo(),
);
}
}
class LayoutDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Flutter Layouts")),
body: Column(
children: [
Container(
padding: EdgeInsets.all(10),
color: Colors.blue,
child: Text("Container Layout", style: TextStyle(color: Colors.white)),
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(Icons.star, size: 50, color: Colors.red),
Icon(Icons.favorite, size: 50, color: Colors.pink),
Icon(Icons.thumb_up, size: 50, color: Colors.green),
],
),
SizedBox(height: 10),
Expanded(
child: GridView.count(
crossAxisCount: 2,
children: List.generate(6, (index) {
return Card(
color: Colors.amber,
child: Center(child: Text("Item ${index + 1}")),
);
}),
),
),
],
),
);
}
}