Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

mongodb - How to query from within Mongoose pre hook in a Node.js / Express app?

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

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.

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();
  });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...