gpt4 book ai didi

node.js - 连接到 Mongoose 并将其与函数一起使用

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:23 25 4
gpt4 key购买 nike

我一直在尝试寻找在我的应用程序启动时连接到 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);

最佳答案

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

关于node.js - 连接到 Mongoose 并将其与函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34209613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com