我知道这是旧帖子,但这是我的解决方案,它采用了启发使用的功能。它用于线程注释,并收集了引用的 MongoDB 文章中提供的概念。我的模型/comment.js 路径中有此代码,并且很可能会将 generateSlug() 函数拉出到 utils.js 文件中并将其重新导入。
function generateSlug() {
let slug = '';
let chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
for ( let i = 0; i < 5; i++ ) {
slug += chars.charAt(Math.floor(Math.random() * chars.length));
}
return slug;
}
CommentSchema.pre('save', function (next) {
let comment = this;
let timestamp = moment(comment.postedAt).format('YYYY.MM.DD.hh:mm:ss');
let slug_part = generateSlug();
let full_slug_part = timestamp + ':' + slug_part;
if ( comment.parent_id ) {
Comment.findOne({'_id': comment.parent_id }, { slug: 1, full_slug: 1 })
.then(parent => {
comment.slug = parent.slug + '/' + slug_part;
comment.full_slug = parent.full_slug + '/' + full_slug_part;
next();
});
} else {
comment.slug = slug_part;
comment.full_slug = timestamp + ':' + slug_part;
next();
}
});