我试图将连接项存储在变量中,以便可以在执行插入,删除等操作的其他方法上重用它。
var MongoClient = require('mongodb').MongoClient;
let _db;
connect = function () {
MongoClient.connect("mongodb://localhost:27017", {useNewUrlParser: true}, function (err, client) {
_db = client.db("SomeDB");
});
};
addTestCollection = function () {
_db.collection('Persons', function (err, collection) {
collection.insertOne({id: 1, firstName: 'Steve', lastName: 'Jobs'});
collection.insertOne({id: 2, firstName: 'Bill', lastName: 'Gates'});
collection.insertOne({id: 3, firstName: 'James', lastName: 'Bond'});
_db.collection('Persons').count(function (err, count) {
if (err) throw err;
console.log('Total Rows: ' + count);
});
});
};
connect();
addTestCollection();
尝试创建集合“人员”的行返回“无法读取未定义的属性'集合'”错误。