Javascript-форум (https://javascript.ru/forum/)
-   Node.JS (https://javascript.ru/forum/node-js-io-js/)
-   -   Несколько запросов (https://javascript.ru/forum/node-js-io-js/60538-neskolko-zaprosov.html)

scorpion95 05.01.2016 18:09

Несколько запросов
 
Проблема вот в чем: написал простенький сервер на NodeJS который использует MongoDB как БД, когда делаю через аякс пост запрос в него первый раз - все гуд. Когда ещё раз - ошибки.



Код сервера:
var http = require("http");
var url = require("url");
var fs = require("fs");
var mongoose = require('mongoose');
var formidable = require('formidable');
var db = mongoose.connection;

http.createServer(function(req, res){
	switch(req.url){
		case "/":
			sendFile("public_html/index.html", res);
			break;
		case "/send":
			var form = new formidable.IncomingForm();
			form.parse(req, function(err, fields, files) {
				db.on('error', console.error);
				db.once('open', function() {
					var movieSchema = new mongoose.Schema({
						  title: { type: String }
						, rating: String
						, releaseYear: Number
						, hasCreditCookie: Boolean
					});

					var Movie = mongoose.model('Movie', movieSchema);
						
					Movie.findOne({ title: fields.name }, function(err, line) {
						if (err) { 
							res.end("Not found");
							return console.error(err);
						};
							  
						  res.end(JSON.stringify(line._doc));
					});
				});

				mongoose.connect('mongodb://localhost/test');
			});
			break;
			
		default:
			res.statusCode = 404;
			res.end("Not found");
	}
}).listen(3306);

function sendFile(fileName, res){
	res.setHeader("Content-Type", "text/html; charset=UTF-8");
	
	var file = new fs.ReadStream(fileName);
	
	file.pipe(res);
	
	file.on("error", function(err){
		res.statusCode = 500;
		res.end("Server Error");
		console.log(err);
	});
	
	res.on("close", function(){
		file.destroy();
	});
}


Помогите, плиз.

Vlasenko Fedor 05.01.2016 18:22

Из рабочего примера. И не забываем закрывать соединение
function connected(callback) {
    db.open(dbConfig.host, dbConfig.db.name, dbConfig.port, dbConfig, callback);
}

connected(function () {
            colFiles.update({_id: id}, minMax, function (err, res) {
                if (err) {
                    logError(err, __line);
                }
                if (res) {
                    console.log('End: ' + (new Date()));
                    console.log('File - ' + file + ' is parsed', __line);
                }
                db.close(); //не забываем
            });
        });


Часовой пояс GMT +3, время: 04:55.