0

I am using mongodb to store express-session docs its work fine with insert and update but failed to delete session from collection i don't know why but it works first time when i restart my server

async function logout(req, res) {
 if (!req.sessionID || !req.session.adminId){
     res.send({status:400,detail:"Invalid Request"})
     return;
 }
 if (sessionStore!=null){
     sessionStore.remove({"_id":req.sessionID},true)
     res.send({status:200,detail:"Logged Out"})
 }
 else {
     res.send({status:400,detail:"Something went wrong"})
 }
}

/*sessionStore here is my collection object e.g db.collection('sessions') as below*/
mongoClient.connect("mongodb://localhost:27017/AdminSessionDb", function(err, db) {
    if (err) {
        console.log('Error connecting to MongoDB-AdminSessionDB', err);
        return;
    }
    else {
        // console.log('Connected to MongoDB-capptinAdminSessions => auth.js');
        adminSessionsCollection = db.collection("sessions");
    }
});
4
  • have you tried without true in your query? Commented Jan 30, 2019 at 13:30
  • yeah i tried infact i tried with deleteMany and remove function , but unfortunately failed Commented Jan 30, 2019 at 13:39
  • and when i restart server it delete fine with all the functions e.g remove,deleteOne , deleteMany .. Commented Jan 30, 2019 at 13:40
  • have you tried _id:ObjectId(your_id) in remove query? Commented Jan 31, 2019 at 4:37

1 Answer 1

2

Try to wrap id in ObectId() as following: db.collection.remove( {"_id": ObjectId("ID")});

async function logout(req, res) {

if (!req.sessionID || !req.session.adminId){
    res.send({status:400,detail:"Invalid Request"})
    return;
}
if (sessionStore!=null){
    sessionStore.remove({"_id": Mongoose.Types.ObjectId(req.sessionID)})
    res.send({status:200,detail:"Logged Out"})
}
else {res.send({status:400,detail:"Something went wrong"})
 }
}

/*sessionStore here is my collection object e.g db.collection('sessions') as below*/
mongoClient.connect("mongodb://localhost:27017/AdminSessionDb", function(err, db) {
    if (err) {
        console.log('Error connecting to MongoDB-AdminSessionDB, err);
        return;
    }
    else {
        // console.log('Connected to MongoDB-capptinAdminSessions => auth.js');
        adminSessionsCollection = db.collection("sessions");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

my sessionId is already a string , anyhow i tried with ObjectId but it show error " Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters "
my req.sessionId is like 2SXBWzAMq6laXsmYtLGqJHpdt3omDesG

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.