Reputation: 3464
Here is the code snipped which runs when I open a webpage from browser, it queries all the users, and just removes the users object who is querying it.
I am trying to do it by equating their _id
's field which is generated by default in mongodb and is always unique, I am able to print each object's _id
field but when i try it in if condition it fails to enter the if condition,
user.find({}, { 'local.name': 1, route_id: 1, stop_number: 1, _id: 1 }, function (err, allusers) {
if (err) throw err;
var len = allusers.length;
for (var index = 0; index < len; index++) {
console.log(allusers[index]._id);
console.log(index);
if (allusers[index]._id === req.user._id) {
console.log("here");
allusers.splice(index, 1);
}
}
res.send(allusers);
})
Here is the output of above:
GET /javascripts/delete_user.js 304 1ms
588f2aded1902a1b08959145
0
58bd116c84fdb70a9c4f34aa
1
can't figure where I am going wrong, and yes, req.user._id
equals to the first user's id i.e. 588f2aded1902a1b08959145
, still does not enters if condition, if someone can please point me in the right direction.
Upvotes: 0
Views: 113
Reputation: 3464
I found the solution to the error, I was removing the object as soon as I found it, which was reducing the length of allusers array and when it will try to reach last index which is now undefined as I spliced it already it was reading the -id property of undefined.
Here is the correct code:
user.find({}, { 'local.name': 1, route_id: 1, stop_number: 1, _id: 1 }, function (err, allusers) {
if (err) throw err;
var len = allusers.length;
var to_remove;
for (var index = 0; index < len; index++) {
if (allusers[index]._id === req.user._id) {
to_remove = index;
}
}
allusers.splice(to_remove, 1);
res.send(allusers);
})
Upvotes: 0
Reputation: 800
Try
if( allusers[index]._id.toString() === req.user._id.toString() ) {
console.log("here");
allusers.splice(index,1);
}
Works for me :)
Upvotes: 1