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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…