我正在编写一个快速应用程序,需要跟踪mongodb数据库中的文档数。我知道可以使用计数器集合或外部插件来实现。我想知道是否以及为什么使用全局变量是错误的。
这就是我想要做的
var counter = noOfDocuments; //assume this is initialized correctly
app.post('/add', function(req, res) {
var data = req.body;
mongoose.connect('mongodb://localhost:27017/sample', {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connection Successful!");
var password =uuid();
password = password +(val+1);
var file = new fileModel({ name: data.name, phoneNo: data.phoneNo , pwd: password ,fileNo : val+1});
// save model to database
file.save(function (err, employee1) {
if (err) {
mongoose.connection.close();
return console.error(err);
}
mongoose.connection.close();
val = val+1;
res.send("Added successfully!")
});
});
});
该代码目前对我来说运行良好,但是由于其异步特性,我不确定在有多个同时用户的情况下是否可以运行。