【发布时间】:2016-04-28 17:46:29
【问题描述】:
我正在尝试构建一个像 bitly 一样充当 URL 缩短器的应用程序。但是,我遇到了障碍,非常感谢您的帮助。我正在使用 mocha 测试我的 Link 模型,并且在我的一个预中间件函数中遇到了错误。在此函数中,我尝试计算所有具有与我刚刚生成的 URL 匹配的缩短 url 的条目的数量,这样我就不会在缩短的链接上加倍。为了做到这一点,我试图在我的模型上调用 Mongoose 的计数函数,但我得到了 TypeError:“无法读取未定义的属性 'count'”。我试图寻找发生这种情况的原因,但无法提出任何建议。
如果您能帮助我弄清楚为什么会发生这种情况,或者有什么更好的方法来生成缩短的链接,我将不胜感激。谢谢!
您可以在下面找到我的链接模型的代码:
'use strict';
let mongoose = require('mongoose'),
config = require('../../config/config'),
schema = mongoose.Schema;
let LinkSchema = new schema({
originalLink: {
type: String,
trim: true,
validate: [
function(link) {
let urlReg = new RegExp("(http|ftp|https)://[\w-]+" +
"(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?");
return urlReg.test(link);
}, 'The URL entered is not valid'
],
required: 'URL to shorten is required'
},
shortenedLink: String
});
LinkSchema.pre('save', function(next) {
let shortLink;
let count;
while (true) {
console.log(`slink: ${shortLink}, count: ${count}`);
shortLink = this.generateShortenedLink(this.originalLink);
mongoose.model['Link'].count({shortenedLink : shortLink}, (err, n) => {
if (err) {
console.log(err);
next();
}
count = n;
});
if (count === 0) {
break;
}
}
this.shortenedLink = shortLink;
next();
});
LinkSchema.methods.generateShortenedLink = function(link) {
let text = "";
let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 8; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return config.appUrl + text;
};
mongoose.model('Link', LinkSchema);
【问题讨论】:
标签: javascript node.js mongodb mongoose typeerror