I've created some express middleware to use on a route that basically takes a server ID given in the url parameters then finds that Server in the mongoDB and checks if the current sessions user ID is equal to the ownerID variable created in the mongoose Server schema. My use for this is I only want users to be able to delete servers they themselves have created I've put loads of console.logs in so I can debug whats going on but I fear this is something outside my limited knowledge! Here is my isOwnServer middleware:
var Server = require('../models/Servers.js');
module.exports = function(req, res, next) {
Server.findById(req.params.id, function(err, server){
console.log('beginning isOwnServer check on server id :' + server._id + " user id: " + req.user._id + " " + server.ownerID);
if(err) return(err);
console.log(req.user._id);
console.log(server.ownerID);
if(server.ownerID === req.user._id){
console.log('your server verified');
next();
} else {
console.log('not your server');
res.send(401);
}
})
};
and the OwnerID variable in the mongoose schema is:
ownerID: {type: Schema.ObjectId, ref: 'User'}
When I attempt to delete a server it just gives me a 401 error, but the console.log(server.ownerID) and console.log(req.user._id) give the exact same ID so I don't see why this middleware is saying the 2 variables are not equal when they appear to be exactly the same Thanks if anyone can help me!
Edit: Even when I use == instead of === the comparison between the variables server.ownerID and req.user._id is still returning false! Even though looking at my console tells me both of these equal 54c52f0f1c339ab8141828fc is this something mongoose is doing thats making them technically not equal even though they are? Do I need to turn these values both into a string before comparing them possibly?