简体   繁体   中英

Mongoose Model Undefined in Pre Middleware

I am trying to construct an application that acts as a URL shortener like bitly. I have hit a snag, however, and would very much appreciate your help. I was in the process of testing my Link model with mocha and was running into errors in one of my pre middleware functions. In this function I attempt to get a count of all the entries that have a shortened url that matches the one that I just generated, so that I don't double up on my shortened links. In order to do this I am trying to call the Mongoose's count function on my model, but I am getting the TypeError: "cannot read property 'count' of undefined". I have tried to search for why this is happening but have been unable to come up with anything.

If you could help me figure out why this is happening or what a better method would be for generating the shortened links, I would very much appreciate it. Thanks!

You can find my code for my Link model below:

'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 is a function, and you're using it as if it were an object.

Try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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