首页 > 解决方案 > Mongoose 方法中这个变量的上下文是什么?

问题描述

在下面的代码中,我看到“this”在 Mongoose 的链接方法中使用。所以,我不知道'this'的上下文是什么以及使用'this'的目的是什么?

PersonSchema
.virtual('name.full')
.get(function () {
  return this.name.first + ' ' + this.name.last;
})
.set(function (setFullNameTo) {
  var split = setFullNameTo.split(' ')
    , firstName = split[0]
    , lastName = split[1];

  this.set('name.first', firstName);
  this.set('name.last', lastName);
});

标签: javascriptnode.jsmongoosethis

解决方案


文档

在模型中间件函数中,this 指的是模型。


在文档中间件函数中,this 指的是文档。


在查询中间件函数中,this 指的是查询。


当您在聚合对象上调用 exec() 时,将执行聚合中间件。在聚合中间件中,this 指的是聚合对象。


的目的this是您可以与数据进行交互。比如改变里面的一个值或者做其他的处理。


推荐阅读