【发布时间】:2018-03-06 05:02:27
【问题描述】:
我正在使用带有 nodejs 的 mongodb。我的 mongodb 实用程序具有以下代码
在 mongodbUtil.js 中:
var MongoClient = require('mongodb').MongoClient
var state = {
db: null,
}
exports.connect = function(url, done) {
if (state.db) return done()
MongoClient.connect(url, function(err, db) {
if (err) return done(err)
state.db = db
done()
})
}
exports.get = function() {
return state.db
}
/* 1 : when is close called */
exports.close = function(done) {
if (state.db) {
state.db.close(function(err, result) {
state.db = null
state.mode = null
done(err)
})
}
}
在 app.js 我有以下代码
var async = require("async");
var express = require("express");
var app = express();
var db = require("./mongodbUtil");
db.connect('mongodb://localhost:27017/mydatabase', function(err) {
if (err) {
console.log('Unable to connect to Mongo.')
process.exit(1)
} else {
app.listen(3000, function() {
console.log('Listening on port 3000...')
})
}
})
app.get('/',function(req,res){
res.send("routes :/insert ")
})
app.get('/insert',function(req,res){
var collection = db.get().collection('insertcollection');
collection.drop();
var obj = {};
for (i=0; i <100000 ; i++){
obj=({id: i, square:i*i,sum:i+i,subtract:i-1,data:"data part 2014"});
collection.insert(obj.table, function (err, result) {
if(err) {
console.log(err);
} else {
console.log(i);
}
});
}
})
我在这段代码中有以下查询
- 我应该什么时候关闭 mongodb 中的连接?这是由nodejs mongodb驱动程序隐式处理的还是只会创建一个连接 在这种情况下游泳池?
- 我应该使用读取偏好和写入偏好设置连接字符串还是应该将其保留为默认值?
- 在插入路径中,只有 ~60000 条记录被插入到集合中。我在 mongodb 插入回调中也没有看到任何错误。仅转储部分数据是否有特殊原因? (我知道批量插入的性能更好,但我很好奇为什么没有报告错误,只转储了部分数据)
【问题讨论】: