Skip to content
techird edited this page Apr 6, 2016 · 1 revision

Step8. 支持文件及元数据删除

上一步:Step7. 添加搜索历史记录

本步骤完整源码在 workflow/step-8 分支上,提交记录为 0f988d4

如果用户不慎上传了一些不和谐的照片,希望删除,那么我们应该怎么处理。

  • 照片在 MongoDB 中有记录,这条记录需要删除
  • 照片保存在 COS 服务中,应该删除
  • 照片在 COS 中的位置保存在 MongoDB 中,所以需要先读取出来
// handle/delete.js
'use strict';

const async = require("co");
const printer = require("../lib/printer");
const mongo = require("../lib/mongo");
const cos = require("../lib/cos");
const ObjectId = require("mongodb").ObjectId;

/**
 * 删除图片及其元数据
 */
const handleDelete = (request, response) => async (function * () {
    const print = printer(request, response);
    const body = request.body;
    const id = body.id;
    
    console.log(body);
    
    // parameter checks
    if (!id) {
        print({ error: "Specific `id` to tell the server which image to delete" });
        return;
    }
    
    // connect to mongo db
    let db;
    try {
        db = yield mongo.connect();
    } catch (mongoError) {
        print({ mongoError });
        return;
    }
    
    // find and delete
    try {
        const collection = db.collection("images");
        
        const query = { _id: ObjectId(id) };
        const found = yield collection.find(query).next();
        
        if (found) {
            const path = found.cos.resource_path;
            const cosDeleteResult = yield cos.delete('image', path);
            
            const mongoDeleteResult = yield collection.deleteOne(query);
            
            print({ cosDeleteResult, mongoDeleteResult }); 
        } else {
            print({ message: `image not found with id "${id}"` });   
        }
        
    } catch (error) {
        console.log(error);
        console.log(error.stack);
        print({ error });
    } finally {
        db.close();
    }
});

module.exports = handleDelete;

上述代码中,用户传入要删除图片的 ID,在 MongoDB 中查出记录对应点 COS 访问信息,通过该访问信息删除在 COS 中的存储。然后再删除在 MongoDB 中的记录。

Postman 执行示意如下:

删除成功

在实际的产品中,可能会采取不真实删除的形式,往往把记录移动到其它表或者打标记的形式。这里作为示例,为的是演示 COS 和 MongoDB 的删除如何进行。

恭喜,您已完成所有步骤,但愿您完全实现了本项目中的功能。现在,可以回到 Workflow 页面查看项目总结。