node.js 写图书管理系统的借阅记录的增删改查怎么写
时间: 2024-12-22 17:19:24 浏览: 0
在Node.js中编写一个图书管理系统,借阅记录的增删改查操作通常会涉及到数据库的操作。这里我们假设使用了Mongoose作为ORM工具,配合MongoDB数据库。以下是一个简单的示例:
1. 首先,定义借阅记录(CheckoutRecord)模型:
```javascript
const mongoose = require('mongoose');
const { Schema, ObjectId } = mongoose;
const checkoutRecordSchema = new Schema({
bookId: { type: ObjectId, ref: 'Book', required: true },
borrowerId: { type: ObjectId, ref: 'User', required: true },
borrowedDate: { type: Date, default: Date.now },
dueDate: { type: Date, required: true },
});
module.exports = mongoose.model('CheckoutRecord', checkoutRecordSchema);
```
2. 增加操作(例如保存新记录):
```javascript
exports.createCheckoutRecord = async (bookId, userId, dueDate) => {
try {
const checkoutRecord = new CheckoutRecord({ bookId, borrowerId: userId, dueDate });
return await checkoutRecord.save();
} catch (error) {
throw error;
}
};
```
3. 删除操作(例如删除特定记录):
```javascript
exports.deleteCheckoutRecord = async (id) => {
try {
return await CheckoutRecord.findByIdAndDelete(id);
} catch (error) {
throw error;
}
};
```
4. 修改操作(例如更新归还日期):
```javascript
exports.updateCheckoutRecord = async (id, updatedData) => {
try {
const record = await CheckoutRecord.findByIdAndUpdate(id, updatedData, { new: true });
if (!record) throw new Error('Record not found');
return record;
} catch (error) {
throw error;
}
};
```
5. 查询操作(例如获取所有借书记录或单条记录):
```javascript
exports.getCheckoutRecords = async () => {
try {
return await CheckoutRecord.find();
} catch (error) {
throw error;
}
};
exports.getSingleCheckoutRecord = async (id) => {
try {
return await CheckoutRecord.findById(id);
} catch (error) {
throw error;
}
};
```
以上只是最基本的示例,实际应用中可能需要加入错误处理、验证输入数据、分页查询等功能,并且考虑到安全性,对敏感操作(如删除)可能会添加额外的权限检查。
阅读全文