要實現一個員工管理系統,可以使用MongoDB作為數據庫存儲員工的信息。以下是一個簡單的示例:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'employeeManagement';
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server");
const db = client.db(dbName);
// 在這里進行數據庫操作
client.close();
});
const employeesCollection = db.collection('employees');
const employee = {
name: 'John Doe',
age: 30,
position: 'Developer',
department: 'IT'
};
employeesCollection.insertOne(employee, function(err, result) {
if (err) throw err;
console.log('Employee added successfully');
});
const query = { name: 'John Doe' };
const newValues = { $set: { position: 'Senior Developer' } };
employeesCollection.updateOne(query, newValues, function(err, result) {
if (err) throw err;
console.log('Employee updated successfully');
});
const query = { name: 'John Doe' };
employeesCollection.deleteOne(query, function(err, result) {
if (err) throw err;
console.log('Employee deleted successfully');
});
employeesCollection.find().toArray(function(err, employees) {
if (err) throw err;
employees.forEach(function(employee) {
console.log(employee);
});
});
你可以根據實際需求對以上代碼進行修改和擴展,例如添加更多字段、實現搜索功能等。