为什么是“这个"?猫鼬的pre-save钩子与post-save-sook钩子中的关键字是否不同? [英] Why is the "this" keyword different in a mongoose pre-save hook versus a post-save hook?

查看:69
本文介绍了为什么是“这个"?猫鼬的pre-save钩子与post-save-sook钩子中的关键字是否不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的相关代码段

This is the relevant snippet of my code

MySchema
  .pre('save', function (next) {
    var self = this;
    console.log(self);
    return next();
  });

MySchema
  .post('save', function (next) {
    var self = this;
    console.log(self);
  });

由于某种原因,在这种情况下,预保存的钩子会提供适当的对象

For some reason, in this situation the pre-save hook gives a proper object

{ farm: 557ce790a893e4e0118059e3,
  _id: 557ce791a893e4e011805a35,
  privileges:
   [ { instanceId: 557ce790a893e4e0118059bb,
       access: 5,
       modelType: 'User' } ],
  public: 0,
  properties: { crop: 'No Crop', name: 'Pirani Tract 50' },
  geometry: { type: 'Polygon', coordinates: [ [Object] ] } }

但是帖子保存挂钩只是记录

but the post save hook simply logs

{ domain: null,
  _events:
   { save: [ [Function: notify], [Function] ],
     isNew: [Function: notify],
     init: [Function] },
  _maxListeners: 0 }

推荐答案

post 中间件将文档作为参数而不是pre中间件所接收的next流控制回调参数.

post middleware receives the document as a parameter instead of the next flow control callback parameter that pre middleware receive.

MySchema
  .post('save', function(doc) {
    console.log(doc);
  });

这篇关于为什么是“这个"?猫鼬的pre-save钩子与post-save-sook钩子中的关键字是否不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆