CRUD(Create, Read, Update, Delete) operations in GraphQL, MongoDB, and PostgreSQL (using pg-promise) based on the typical SQL employees
table.
GraphQL:
- Create (Mutation):
mutation {
createEmployee(input: { name: "John Doe", department: "IT", hireDate: "2022-03-01" }) {
id
name
department
hireDate
}
}
- Read (Query):
query {
employees {
id
name
department
hireDate
}
}
- Update (Mutation):
mutation {
updateEmployee(id: "123", input: { name: "Updated Name" }) {
id
name
department
hireDate
}
}
- Delete (Mutation):
mutation {
deleteEmployee(id: "123") {
id
name
department
hireDate
}
}
MongoDB:
// Assuming you have a MongoDB connection and a collection named 'employees'
// Create (Insert)
db.employees.insertOne({
name: "John Doe",
department: "IT",
hireDate: new Date("2022-03-01")
});
// Read (Find)
const allEmployees = db.employees.find().toArray();
// Update (UpdateOne)
db.employees.updateOne(
{ _id: ObjectId("employee_id_here") },
{ $set: { name: "Updated Name" } }
);
// Delete (DeleteOne)
db.employees.deleteOne({ _id: ObjectId("employee_id_here") });
PostgreSQL (pg-promise):
// Assuming you have a pg-promise connection and a table named 'employees'
// Create (Insert)
const newEmployee = await db.one(
'INSERT INTO employees(name, department, hire_date) VALUES($1, $2, $3) RETURNING *',
["John Doe", "IT", new Date("2022-03-01")]
);
// Read (Select)
const allEmployees = await db.any('SELECT * FROM employees');
// Update (Update)
const updatedEmployee = await db.one(
'UPDATE employees SET name = $1 WHERE id = $2 RETURNING *',
["Updated Name", 123]
);
// Delete (Delete)
const deletedEmployee = await db.one(
'DELETE FROM employees WHERE id = $1 RETURNING *',
[123]
);
These examples demonstrate basic CRUD operations in GraphQL, MongoDB, and PostgreSQL. Adapt the queries and mutations based on your actual GraphQL schema and database schema. Additionally, ensure you have proper error handling and input validation in your actual implementation.
Top comments (0)