Shahrzad A Shahrzad A - 1 year ago 96
Node.js Question

how to remove a value from an array in database using nodejs and mongoose

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


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) {
if (!result) {
res.send('whooops, you dont have any media yet :)')
} else {
console.log('its here')
for (var i in result.mediaid) {
if (i == medid) {
user.update({ tokenid: token }, { $pull: { mediaid: medid } }, function(err, result2) {
if (err) {
res.send('an error happened')
} else {
//res.send('your tokenid is '+ token)
} else {
res.send('media id didnt match')


My database has 3 objects
which are strings and
which is an array

Also, I want to check if my
array is null or not and exist is this code

mediaid !== 'undefined' && mediaid.length > 0

Answer Source

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){
    if(result.mediaid[i] === medid){
        user.update({tokenid: token}, {$pull: {mediaid: medid}},function(err, result2){
        if (err){
            res.send('an error happened');
            //res.send('your tokenid  is '+ token)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download