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

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

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

但是,它似乎没有访问.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(); }); 

不幸的是,它没有被很好的logging(在Document.js API文档中没有提及它),但是文档可以通过constructor字段访问他们的模型 – 我一直使用它来logging来自插件的东西,这使我能够访问他们连接到哪个模型。

 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不在文档中。

如果你需要模型,你可以随时检索它,如下所示。 但更聪明的做法是在创build时将模型分配给一个variables。 然后在你想要的地方使用这个variables。 如果它在另一个文件中,那么使用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 })