Question:
The problem is as shown in the title. When the front end requests two interfaces that need to operate data from the back end at the same time, the back end reports an error, which is felt to be caused by the fact that the previous database has not been shut down at the time of the second request.
The code is as follows:
db.js:
var settings = require(‘../settings’),
Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server;
module.exports = new Db(settings.db, new Server(settings.host, settings.port), {safe: true});
user.js
user.checkCollect = function(username, artid, callback) {
mongodb.collection('users', function (err, collection) {
if (err) {
mongodb.close();
return callback(true);
}
collection.findOne({
"name": username
}, function(err, post) {
if (err) {
mongodb.close();
return callback(err);
}
if (! post) {
mongodb.close();
return callback(true);
}
var userCollections = post.collections
, hasCollected = false
;
for (var i = 0, len = userCollections.length; i < len; i++) {
if (userCollections[i] === artid) {
hasCollected = true;
break;
}
}
callback(false, hasCollected);
mongodb.close();
})
})
}
}
This is the code of database operation. After testing, it is found that this problem will occur no matter whether the same interface or different interfaces are requested, as long as two or more requests are made at the same time. Please advise Daniel!
Looks like you’re using
node-mongodb-native
Drive. The old version did use DB as a top-level object, but the current driver usually suggests usingMongoClient
Used for top-level objects. Direct reference to driver documentation:
https://github.com/mongodb/no …
pay attention toMongoClient
The connection pool is maintained, so it is usually not necessary to shut down your application before it exits, leaving a single instance.MongoClient
Just use it all the time.