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