Home > other >  Nodejs Get fetch values excluding matching field array value from Mongo
Nodejs Get fetch values excluding matching field array value from Mongo

Time:05-19

How to make a find in Nodejs to get the values excluding the Given ID.

{"_id": 
    {"$oid": "1"},  
    "image_name": "img1.jpg",  
    "price": 120,  
    "user": [{
        "$oid": "userid1"
    }],
    "category": [{
        "$oid": "cat1"
    }]
    "__v": 1
}
{"_id": 
    {"$oid": "2"},  
    "image_name": "img2.jpg",  
    "price": 120,  
    "user": [{
        "$oid": "userid2"
    }],
    "category": [{
        "$oid": "cat2"
    }]
    "__v": 1
}
{"_id": 
    {"$oid": "3"},  
    "image_name": "img3.jpg",  
    "price": 120,  
    "user": [{
        "$oid": "userid3"
    }],
    "category": [{
        "$oid": "cat3"
    }]
    "__v": 1
}

For example if the userid is 2, i want to exclude the user that has id 2 and get all other datas. like

{"_id": 
    {"$oid": "1"},  
    "image_name": "img1.jpg",  
    "price": 120,  
    "user": [{
        "$oid": "userid1"
    }],
    "category": [{
        "$oid": "cat1"
    }]
    "__v": 1
}
{"_id": 
    {"$oid": "3"},  
    "image_name": "img3.jpg",  
    "price": 120,  
    "user": [{
        "$oid": "userid3"
    }],
    "category": [{
        "$oid": "cat3"
    }]
    "__v": 1
}

Like above. Please help. I tried the $expr, $not, $in method But its throwing back an error, Which is

val[key] = val[key].map(v => _castExpression(v, schema, strictQuery)); TypeError: val[key].map is not a function

Edit: Below is the code that I tried and Got up with above error

app.get("/get-images", (req, res) => {
image
    .find(
        {
        $expr: {
            $not: {
                $in: [{
                    _id: req.query.userId
                }]
            }
        }
    }
    )
    .populate("user")
    .populate("category")
    .then((img) => {
        res.status(200).send(img);
    });

});

CodePudding user response:

Try this

image.find({
  _id: { $ne: req.query.userId }
})

$ne will give you all the documents whose _id is not equal to the given value.

  • Related