I’m building REST APIs in node.js using express.js library. For the embedded data stored in mongodb as json object, I’m trying to get specific data by filtering, thereby using the aggregate match to achieve so.
For the users collection, I’ve the data as below
[
{
unique_key:"1",
user_form:
{
user_details:
{
first_name:"Tely",
last_name:"Zed"
}
}
},
{
unique_key:"2",
user_form:
{
user_details:
{
first_name:"Rock",
last_name:"Monty"
}
}
}
]
I want to get data of user by searching name. So I’m using aggregate method and then using match operator to achieve it. User is the name of the model. For filtering I’m using below aggregate method on User model.
User.aggregate([
{
$match: {
user_form:
{
user_details:
{
first_name: req.body.user_form.user_details.first_name
}
}
}
}
])
.exec(function(err,filteredUsers){
if(filteredUsers) {
console.log(filteredUsers);
res.json({
"msg": "Successfully gets the filtered users",
"data": filteredUsers,
"success": true
});
} if(err){
res.json({
"msg":"Error occured while filtering users",
"error": err ,
"success":false
});
}
})
Now when I’m posting request from postman with searching with first_name as Rock in postman //body as shown below.
{
user_form:
{
user_details:
{
first_name:"Rock"
}
}
}
So upon hitting send, I’m getting below response in postman, so I’m not able to get filtered //data instead getting an empty array.
{
"msg": "Successfully gets the filtered users",
"data": [],
"success": true
}
So please tell what should I do to filter data .