0

shortener嗨,我收到错误“OverwriteModelError:编译后无法覆盖模型。” 在以下代码段中。

var mongoose = require('mongoose');
var http    = require('http');
var server  = http.createServer( function(httpRequest, httpResponse) {

    var urls    = httpRequest.url.split("/");
    var parts   = [];
    for(var i = 0; i < urls.length; i += 1) {
        if(urls[i] === "") continue;
        parts.push(urls[i]);
    }

    console.log(parts);

    if( parts.length === 0 ) {
        httpResponse.writeHead( 400 );
        httpResponse.end();
    }

    mongoose.connect("mongodb://localhost/shortener");

    var db      = mongoose.connection;
    var now     = new Date();
    var shortener   = {};

    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function() {

        var urlSchema = mongoose.Schema({
            slug: String,
            url: String
        });
        shortener = mongoose.model("shortener", urlSchema);

        if( parts.length === 2 ) {

            //This is a set
            var shortUrl = new shortener({
                slug: now.getTime().toString(36),
                url: decodeURIComponent(parts[1])
            });
            shortUrl.save( function(error, newUrl) {
                httpResponse.writeHead( 200, {
                    'Content-Type': 'application/json'
                } );
                httpResponse.end(httpRequest.hostname + newUrl.slug);
            } );

        } else if( parts.length === 1 ) {

            //This is a get
            shortener.find( {
                slug: parts[0]
            }, function(error, oldUrl) {
                httpResponse.writeHead( 302, {
                    'Location': oldUrl.url
                } );
            } );

        }
    });

    db.close();

} ).listen(7000);
4

1 回答 1

0

mongoose.model 只能在您的代码中调用一次。尝试将猫鼬代码放在 createServer 回调之外,每次请求到达服务器时都会调用该回调,从而尝试重新注册模型。

于 2013-08-13T10:41:38.343 回答