gpt4 book ai didi

node.js - 写操作前的 MongoDB Nodejs 钩子(Hook)

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:11 25 4
gpt4 key购买 nike

我正在使用nodejs的mongodb驱动程序,我想在我的所有集合上添加last_update字段,我希望每当有写入操作时在该字段上设置新日期。

我正在使用自己的包来扭曲 mongoDB 驱动程序,因此替换 native 函数是一个选项。

我尝试在谷歌中查找写入之前是否有钩子(Hook),但没有找到任何内容,我想替换更新,updateMany,insert,insertMany,但如果有更多写入功能,我不知道我会想念它们,实现这一目标的最佳方法是什么?

最佳答案

您可以使用一些元编程魔法来实现这一点。检查下面的代码和 repl link


function collectionProxy(obj) {

let handleInsertMany = function(list){
return list.map((item) => ({...item, last_updated: Date.now()}))
}

let handler = {
get(target, propKey) {
return function (args) {
// List all the update/ insert queries you want to use
switch(propKey){
case 'insertMany':{
args = handleInsertMany(args);
break;
}
}
let result = obj[propKey].apply(this, args);
console.log(propKey + ' -> ' + JSON.stringify(args));
return result;
};
},
printArgs(args){
args.forEach( arg => console.log)
},
handleInsertMany(list){

}
};
return new Proxy(obj, handler);
}

let collection = {
insertMany(...list){
return list;
}
};


let proxy = collectionProxy(collection);
proxy.insertMany([{a : 1}, {a : 2}, {a : 3}]);

您可以将其作为 JS 模块,初始化一次并导出新的代理集合。

关于node.js - 写操作前的 MongoDB Nodejs 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56421803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com