Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save iamnabeelrahman/7636ee6183875dd8252fe85958a8798f to your computer and use it in GitHub Desktop.

Select an option

Save iamnabeelrahman/7636ee6183875dd8252fe85958a8798f to your computer and use it in GitHub Desktop.
const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.use(express.json());
// fetch all tasks
//delete task
// write logic for first finding task and then updating in update api
mongoose
.connect(`mongodb://localhost:27017/todos`)
.then(() => console.log("DB Connected!"))
.catch(() => console.log("Error in connecting DB"));
const taskSchema = new mongoose.Schema(
{
taskName: {
type: String,
require: true,
},
description: {
type: String,
required: true,
min: [13, "Description should be at least of 13 characters"],
},
isCompleted: Boolean,
},
{ timestamps: true }
);
const task = mongoose.model("task", taskSchema);
// body, query, params, headers, cookies etc etc etc
app.post("/", async (req, res) => {
try {
const { description, taskName } = req.body;
if (!description || !taskName) {
return res.status(500).json({
message: "All feilds are required",
});
}
const newTask = await task.create({
taskName,
description,
});
res.status(200).json({
success: true,
message: "Task created successfully!",
task: newTask,
});
} catch (error) {
res.status(401).json({
success: false,
message: "Server error please try again!",
});
}
});
app.put("/:id", async (req, res) => {
try {
const { id } = req.params;
const updateTask = await task.findByIdAndUpdate(id, {
isCompleted: true
});
res.status(200).json({
success: true,
message: `${updateTask.taskName} is marked completed`
})
} catch (error) {
res.status(500).json({
success: false,
message: "Server error please try again!",
});
}
});
const PORT = 3002;
app.listen(PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment