繁体   English   中英

如何从Node.js / Express应用程序中的Mongoose pre hook中查询?

[英]How to query from within Mongoose pre hook in a Node.js / Express app?

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

我有一个预先'保存'钩子,我想用它为我自动生成一个博客/想法slug。 这工作正常,除了我要查询的部分,以查看是否有任何其他现有帖子具有相同的slug继续之前。

但是,看来this并没有获得.find或.findOne(),所以我不断收到一个错误。

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

  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字段访问它们的模型 - 我一直用它来从插件中记录东西,这让我可以访问他们所依赖的模特。

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();
    });
});

根据您的情况,您应该能够:

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);
});

this你有文件,而不是模型。 方法findOne不存在于文档中。

如果您需要的型号,你可以随时取回它作为显示在这里 但更聪明的是在创建时将模型分配给变量。 然后在任何地方使用此变量。 如果它在另一个文件中,那么使用module.exports并要求在项目的任何其他位置获取它。 像这样的东西:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/dbname', function (err) {
// if we failed to connect, abort
if (err) throw err;
var IdeaSchema = Schema({
    ...
});
var IdeaModel = mongoose.model('Idea', IdeaSchema);
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'
    IdeaModel.findOne({slug: idea.slug}, function(err, doc) {
        console.log(err);
        console.log(doc);
    });

    //console.log(idea);
    next();
   });
// we connected ok
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM