【发布时间】:2015-12-30 23:33:26
【问题描述】:
我正在尝试做一些相对简单的事情,并且每次尝试执行“插入”时都会突然遇到“服务器 ...-a.mongolab.com:36648 套接字已关闭”错误。
读取似乎可以正常工作,但插入似乎每次都会出错,我不确定这是我的代码(最近进行了微小的更改),还是可靠性问题我在 MongoLab 使用的免费服务器(最近显示自己宕机了几分钟)。
奇怪的是,记录本身似乎保存得很好,我只是得到了错误!
谁能看到我的代码有问题,或者这可能是其他问题?
var mongoClient = require('mongodb').MongoClient;
var http = require('http');
var connectionString = "...";
var pictureWallsCollectionName = 'PictureWalls';
//this is what barfs. see *** details
exports.saveWall = function (req, res) {
//reformat
var toSave = {
_id: req.body.wallId,
pictures: req.body.pictures
};
var status;
mongoClient.connect(connectionString, function (err, db) {
if (err) { return console.error(err); }
var collection = db.collection(pictureWallsCollectionName);
//*** no err yet... ***
collection.insert(
toSave,
function (error, response) {
//*********************
//*** err here! ******
//*********************
db.close();
if (error) {
console.error(error);
//bad
status = 500;
}
else {
console.log('Inserted into the ' + collection_name + ' collection');
//good
status = 200;
}
});
response.status(status).end(http.STATUS_CODES[status]);
});
}
//this seems to work pretty reliably. including it just in case it's relevant
exports.findByWallId = function (req, res) {
var id = req.params.id;
console.log('Retrieving wall: ' + id);
mongoClient.connect(connectionString, function (err, db) {
if (err) { return console.dir(err); }
var collection = db.collection(pictureWallsCollectionName);
collection.findOne(
{ _id: id },
function (err, item) {
db.close();
if (err) {
console.error(err);
//something bad happened
var status = 500;
res.status(status).end(http.STATUS_CODES[status]);
}
else {
console.log('Found wall with ID ' + id);
//reformat and send back in the response
res.send({
wallId: item._id,
pictures: item.pictures
});
}
}
);
});
};
【问题讨论】:
标签: node.js mongodb sockets azure mlab