'Cannot use a session that has ended
Sorry to bother you all but we have been facing this problem with this code.
app.get('/site', (req, res, next) => {
let listOfScreens = [];
const client = MongoClient.connect(url, function(err, db) {
if (err) throw err;
var database = db.db("Webxplorerdb");
let category = req.query.category;
let nbScreen = req.query.nb;
let randomNum;
let site;
let social;
let i;
if (category == 0) {
social = database.collection('Social Media');
for (i = 0; i < nbScreen; i++) {
randomNum = Math.floor(Math.random() * socialmediadocs);
site = social.findOne({ _id: randomNum },
function(err, result) {
if (err) throw err;
listOfScreens.push(result);
})
}
res.json(listOfScreens);
db.close();
}
});
});
I have only shown a part of the code but the rest is the same if condition but with different variables. The problem that we get is that we either get the error "Cannot use a session that has ended" or if we delete the db. close() line, the server sends an empty list(due to the declaration of listOfScreens before) instead of a list of documents that we get from the db with each iteration. So my question is how to solve that problem. I thank you all in advance for your answers.
Solution 1:[1]
The reason this doesn't work is the usage of NEW.contract_id in the AFTER DELETE trigger:
UPDATE contracts SET updated_at = now() WHERE contracts.contract_id = NEW.contract_id;
Per the Triggers on Data Changes documentation, NEW is NULL for DELETE triggers.
Updating the code to use OLD instead of NEW fixes the issue:
CREATE OR REPLACE FUNCTION update_campaign_target() RETURNS trigger AS $update_campaign_target$
BEGIN
IF TG_OP = 'DELETE'
THEN
UPDATE contracts SET updated_at = now() WHERE contracts.contract_id = OLD.contract_id;
ELSE
UPDATE contracts SET updated_at = now() WHERE contracts.contract_id = NEW.contract_id;
END IF;
RETURN NULL;
END;
$update_campaign_target$ LANGUAGE plpgsql;
Thanks to Anthony Sotolongo and Belayer for your help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom Lagier |
