When I place a MongoDB query inside router.get() in /routes/index.js
like this:
/* GET home page. */
router.get('/', function(req, res, next) {
console.log('1 rendering index performing a DB query');
performQuery(query, function(dbData) {
res.render('./home/index', dbData);
});
});
I get this console output:
[nodemon] starting `node ./bin/www`
app.use(/, routes)
SERVER READY on port 3000
SOCKET.IO client: /#V261JQOrV3aEyu34AAAA CONN
rendering index performing a DB query -------------------------------------------------> 1
GET / 200 744.652 ms - 4054 -----------------------------------------------------------> 1
SOCKET.IO client: /#V261JQOrV3aEyu34AAAA DISCONN
GET /stylesheets/main.css 304 4.166 ms - -
GET /images/logo-icon-90.png 304 0.514 ms - -
GET /public/js/libs/socket.io/socket.io.js 304 3.888 ms - -
GET /public/js/libs/jquery/jquery-2.1.4.min.js 304 15.758 ms - -
rendering index performing a DB query -------------------------------------------------> 2
GET / 304 363.686 ms - - --------------------------------------------------------------> 2
SOCKET.IO client: /#w4kVulgNfEfnJJPOAAAB CONN
I checked if there was another error of some sort taking out the MongoDB query and just rendering '/' and then console outputs just one GET request to '/'. The only thing changing between getting 1 or 2 GET request is placing the MongoDB query.
performQuery.js
content:
MongoClient.connect(mongoURL + dbName, function(err, db) {
assert.equal(err, null);
const cursor = db.collection(collection).aggregate([
{ $match: query.justVars},
{ $group: {
_id: {var1: '$somevar', var2: '$anothervar'},
takeScore: {$first: '$score'}
}
},
{ $sort: {score: -1}},
{ $group: {
_id: '$_id.var1',
vars2: { $push: {
name: '$_id.var2',
score: '$takeScore'
}
},
sumScore: { $sum: '$score'}
}
},
{ $sort: {sumScore: -1}}
]);
cursor.toArray(function(error, documents) {
assert.equal(error, null);
callback(documents);
db.close();
});
});
QUESTION
Why is there 2 GET request to '/' and not just one?
A possible problem is the cursor.toArray
. Can you console.log
here:
cursor.toArray(function(error, documents) {
assert.equal(error, null);
console.log(documents);
callback(documents);
db.close();
});
and check how many extra lines do you have in the console?
It seems that you retrieve 2 documents from the database and in this iteration you call 2 times the callback. You have to call the callback ONLY when the iteration will finish.
What is the SOCKET.IO logs? Is it possible that you have open 2 different tabs on the browser and when you restart the application they are trying to connect automatically and that's why it feels like you have 2 GET requests?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.