【问题标题】:Why does .pre find query return undefined in this case?为什么 .pre find 查询在这种情况下返回未定义?
【发布时间】:2018-12-21 23:43:27
【问题描述】:

我刚刚了解了 pre/post 钩子,我想对其进行测试。当我尝试 console.log 它(所以我可以看到它按预期工作)时,我得到了未定义。我不明白为什么。

我尝试将 this.nume 更改为 this["nume"]。我认为它可能会起作用(因为在编程中有时你会得到意想不到的结果),即使是同样的事情。不幸的是,它没有用:(

我有这个预钩子:

someriSchema.pre('find', function(next) {
    console.log(this.nume);
    next();
});

还有这个架构:

var someriSchema = new mongoose.Schema({
    nume: {type: String, required: true}
});

(我有一个 GET 路由,可以在其中进行查找查询)。

为什么返回未定义?我不明白。我做错了吗?

///获取路由:

router.get('/judet/:id([0-9]{2})', middleware.access2, function(req, res)
{
      var title = "Dashboard";
      Somer.find({}, function(err, user)
      {
        if(err)
        {
            console.log(err);
        }
        else
        {
            res.render("dashboard", {title: title, id:req.params.id, someri:user});
        }
      });
});

【问题讨论】:

  • 能否请您发布 GET 路由或至少 .find() 调用?
  • @BenSower 我添加了获取路线。
  • 好的,我刚刚看到您不想编辑查询,而是文档本身,除非挂钩是文档中间件,而不是查询中间件,否则您不能这样做。

标签: node.js mongodb mongoose


【解决方案1】:

在“查找”middleware 中,this 指的是正在执行的查询,而不是集合中的文档。

因此,除非您的查询包含 nume 字段,否则 this.nume 将是未定义的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 2016-03-02
  • 2014-09-12
  • 2018-04-26
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多