连接到Mongoose并使用它与函数

时间:2015-12-10 18:58:16

标签: node.js mongodb mongoose

当我的应用程序启动时,我一直在尝试找到连接到mongoose的方法,然后使用该连接从那时起查询数据库,而不必重新连接全部并触发我一直得到的错误,但我不知道该怎么办。这是我刷新页面时遇到的错误(localhost:8080):

'connection error: { [Error: Trying to open unclosed connection.] state: 1 }'

var http = require("http");
var mongoose = require("mongoose");
var mongodata = [];

function RequestHandler(request, response) {
    console.log("Request received.");

    mongoose.connect("mongodb://localhost:27017/test");
    var db = mongoose.connection;
    db.on("error", console.error.bind(console, "connection error:"));
    db.once("open", function(callback) {
            console.log("Connected.");

    var Schema = mongoose.Schema;
    var motorSchema = new Schema ({
            RPM: String,
            Horsepower: String
    });

    var Motor = mongoose.model("Motor", motorSchema);

            Motor.find(function(err, motors) {
                    console.log(motors[2].Horsepower);
                    var i;

                    for (i=0; i < motors.length; i++) {
                            mongodata[i] = motors[i];
            }
    });
});

            response.write("Test.");
            response.end();
}

http.createServer(RequestHandler).listen(8080);

1 个答案:

答案 0 :(得分:0)

var http = require("http");
var mongoose = require("mongoose");
var mongodata = [];
mongoose.connect("mongodb://localhost:27017/test");
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function(callback) {
    console.log("Connected.");
});
var Schema = mongoose.Schema;
var motorSchema = new Schema({
    RPM: String,
    Horsepower: String
});

var Motor = mongoose.model("Motor", motorSchema);

function RequestHandler(request, response) {
    console.log("Request received.");


    Motor.find(function(err, motors) {
        console.log(motors[2].Horsepower);
        var i;

        for (i = 0; i < motors.length; i++) {
            mongodata[i] = motors[i];
        }
    });


    response.write("Test.");
    response.end();
}
http.createServer(RequestHandler).listen(8080);