0

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);
    });

});

2
  • please provide more detail on where do you get error and make sure that val[key] has value and it's an array Commented May 17, 2022 at 13:40
  • @1sina1 did edited the question, please answer, Commented May 17, 2022 at 14:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.