Reputation: 49
I'm trying to remove a value from an array in my database which I get from url.
I use the code below but I get nothing. It doesn't go to the for
loop.
app.get('/remove/:medid/:tokenid', function(req, res) {
var medid = req.params.medid;
var token = req.params.tokenid;
var query = { tokenid: token, mediaid !== 'undefined' && mediaid.length > 0 }
user.find(query).exec(function(err, result) {
if (err) {
res.send('erooooooor')
}
if (!result) {
res.send('whooops, you dont have any media yet :)')
} else {
console.log('its here')
for (var i in result.mediaid) {
console.log(i)
if (i == medid) {
user.update({ tokenid: token }, { $pull: { mediaid: medid } }, function(err, result2) {
if (err) {
res.send('an error happened')
} else {
console.log('deleted')
//res.send('your tokenid is '+ token)
}
})
} else {
res.send('media id didnt match')
}
}
}
});
});
My database has 3 objects userid
and tokenid
which are strings and mediaid
which is an array.
Also, I want to check if my mediaid
array is null or not and exist is this code
mediaid !== 'undefined' && mediaid.length > 0
Upvotes: 0
Views: 282
Reputation: 1790
You have got your json syntax incorrect in following line
var query = {tokenid: token, mediaid !== 'undefined' && mediaid.length > 0}
You should probably just let your query be based on token id.
var query = {tokenid: token};
Also when you write for(var i in result.mediaid)
, for each iteration of loop, the variable 'i' is assigned the index of current element, not its value. So your if condition should be modified to check result.mediaid[i] == medid
instead of i == medid
. Modified loop should look something like:
for(var i in result.mediaid){
console.log(i);
if(result.mediaid[i] === medid){
user.update({tokenid: token}, {$pull: {mediaid: medid}},function(err, result2){
if (err){
res.send('an error happened');
}
else{
console.log('deleted');
//res.send('your tokenid is '+ token)
}
});
}
}
Upvotes: 2
Reputation: 2955
Please, you can replace to:
app.get('/remove/:mediaid/:tokenid', function(req, res){
var medid = req.params.mediaid;
var token = req.params.tokenid;
var query = {tokenid: token, mediaid !== 'undefined' && mediaid.length > 0}
UPDATED:
I recommended that print after console.log(medid, token);
I hoped help you - Jose Carlos Ramos
Upvotes: 0