如何从 Node.js/Express 应用程序中的 Mongoose pre hook 中查询? [英] How to query from within Mongoose pre hook in a Node.js / Express app?

查看:11
本文介绍了如何从 Node.js/Express 应用程序中的 Mongoose pre hook 中查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 Mongoose ORM 的 MongoDB 在 Node.js/Express 中构建一个基本博客.

I'm building a basic blog in Node.js / Express using MongoDB w/ Mongoose ORM.

我有一个预先保存"的钩子,我想用它来为我自动生成一个博客/想法 slug.这工作得很好,除了我想在继续之前查询以查看是否还有其他具有相同 slug 的现有帖子的部分.

I have a pre 'save' hook that I'd like to use to auto-generate a blog/idea slug for me. This works fine and well, except for the part where I want to query to see if there are any other existing posts with the same slug before continuing.

但是,this 似乎没有访问 .find 或 .findOne() 的权限,因此我不断收到错误消息.

However, it appears that this does not have access to .find or .findOne() and so I keep getting an error.

解决这个问题的最佳方法是什么?

What's the best way to approach this?

  IdeaSchema.pre('save', function(next) {
    var idea = this;

    function generate_slug(text) {
      return text.toLowerCase().replace(/[^w ]+/g,'').replace(/ +/g,'-').trim();
    };

    idea.slug = generate_slug(idea.title);

    // this has no method 'find'
    this.findOne({slug: idea.slug}, function(err, doc) {
      console.log(err);
      console.log(doc);
    });

    //console.log(idea);
    next();
  });

推荐答案

不幸的是,它没有很好地记录(在 Document.js API 文档),但文档可以通过 constructor 字段访问它们的模型 - 我一直使用它来记录插件中的内容,这给了我访问他们附加到的模型.

Unfortunately, it's not documented very well (no mention of it in the Document.js API docs), but Documents have access to their models through the constructor field - I use it all the time for logging things from plugins, which gives me access to which model they're attached to.

module.exports = function readonly(schema, options) {
    schema.pre('save', function(next) {
        console.log(this.constructor.modelName + " is running the pre-save hook.");

        // some other code here ...

        next();
    });
});

对于您的情况,您应该能够:

For your situation, you should be able to do:

IdeaSchema.pre('save', function(next) {
    var idea = this;

    function generate_slug(text) {
        return text.toLowerCase().replace(/[^w ]+/g,'').replace(/ +/g,'-').trim();
    };

    idea.slug = generate_slug(idea.title);

    // this now works
    this.constructor.findOne({slug: idea.slug}, function(err, doc) {
        console.log(err);
        console.log(doc);
        next(err, doc);
    });

    //console.log(idea);
});

这篇关于如何从 Node.js/Express 应用程序中的 Mongoose pre hook 中查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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