当我运行我的代码时,我收到一个错误 我想要做的是当有人登录我的网站时,它会将IP和其他数据记录到数据库中。它似乎工作,但后来我得到这个错误,它退出我的应用程序
{ [Error: Trying to open unclosed connection.] state: 1 }
Connection to database has been established
/home/azura/node_modules/mongoose/lib/index.js:343
throw new mongoose.Error.OverwriteModelError(name);
^
OverwriteModelError: Cannot overwrite `dataType` model once compiled.
at Mongoose.model (/home/azura/node_modules/mongoose/lib/index.js:343:13)
at Namespace.<anonymous> (/home/azura/Desktop/dbWrite.js:19:37)
at Namespace.EventEmitter.emit (events.js:95:17)
at Namespace.emit (/home/azura/node_modules/socket.io/lib/namespace.js:205:10)
at /home/azura/node_modules/socket.io/lib/namespace.js:172:14
at process._tickCallback (node.js:415:13)
我使用的代码是:
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
io.on("connection", function (socket) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
dataBase.on("error", console.error);
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
time: Number
});
var collectionOfData = mongoose.model("dataType", collectedData);
var Maindata = new collectionOfData({
ipAddress: ip,
time: 100000000000000000
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
http.listen(10203, function () {
console.log("Server is up");
});
index.html文件没有什么重要的。 我只是想知道为什么我会收到这个错误。 我该怎么做才能解决它?
答案 0 :(得分:1)
将此代码放在连接范围之外。无需为每种类型创建架构都有新的连接事件。
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
dataBase.on("error", console.error);
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
time: Number
});
var collectionOfData = mongoose.model("dataType", collectedData);
io.on("connection", function (socket) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
time: 100000000000000000
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
答案 1 :(得分:0)
每次进入连接时,&#34;连接&#34;事件将被释放,所以
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
将执行manny times,这会导致错误。