繁体   English   中英

在预中间件中未定义的猫鼬模型

[英]Mongoose Model Undefined in Pre Middleware

我正在尝试构建一个像bitbit一样充当URL缩短器的应用程序。 但是,我遇到了麻烦,非常感谢您的帮助。 我当时正在用Mocha测试我的Link模型,并且在我的中间件前功能之一中遇到错误。 在此函数中,我尝试获取所有具有与我刚生成的URL匹配的缩短URL的条目的计数,以使我不会在缩短的链接上加倍。 为了做到这一点,我试图在模型上调用Mongoose的count函数,但是我得到了TypeError:“无法读取未定义的属性'count'”。 我试图搜索为什么会发生这种情况,但无法提出任何建议。

如果您可以帮助我弄清楚为什么会这样,或者生成缩短链接的更好方法是什么,我将不胜感激。 谢谢!

您可以在下面找到我的Link模型的代码:

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

mongoose.model是一个函数,您就像在使用它一样是一个对象。

尝试以下方法:

mongoose.model('Link').count(...);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM