在 Post Hooks 中修改 Mongoose 对象 [英] Modify Mongoose Object in Post Hooks
本文介绍了在 Post Hooks 中修改 Mongoose 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在像 post findOneAndUpdate 这样的 post 钩子中修改 mongoose 对象,但是因为它是 mongoose 对象,所以我不能像下面的例子那样向它添加任何属性
I want to modify mongoose object in post hooks like post findOneAndUpdate, but since it is mongoose object I cannot add any property to it like in the following example
MyShema.post('findOneAndUpdate', function(doc) {
doc["new_field"] = 2;
return doc;
});
返回的这个文档没有 new_field,我该如何处理?
this doc returned is not having new_field, how do I go about this ?
推荐答案
我发现工作的是猫鼬的转换属性,它做了类似的事情
What I found working is the transform property of the mongoose which does something similar
if (!Myschema.options.toObject) Myschema.options.toObject = {};
Myschema.options.toObject.transform = (doc, modified_doc) => {
modified_doc["new_field"] = 2;
return modified_doc;
};
这篇关于在 Post Hooks 中修改 Mongoose 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文