I want to get an user's friends from MongoDB by using NodeJS.
In MongoDB, when I write the query, it works. The result is what I want.
However, I used the same query but I can't get same result in NodeJS. It returns an empty array. When I delete the $match part, It returns some records. I think $match part has some problem that I couldn't catch.
The queries and result are so clean, below :
MongoDB User Document Example
{
"_id" : ObjectId("5cb14fd7db537905c89e0a72"),
"email" : "canmustu@gmail.com",
"username" : "canmustuu",
"inbox" : [],
"friends" : [
{
"user" : {
"id" : ObjectId("5cb18680aa024b2d441f93cc")
}
},
{
"user" : {
"id" : ObjectId("5cb18680aa024b2d441f93cd")
}
},
{
"user" : {
"id" : ObjectId("5cb18680aa024b2d441f93ce")
}
}
],
"friend_requests" : [],
"created_at" : ISODate("2019-04-13T02:56:23.132Z")
}
MongoDB Query
db.getCollection('users').aggregate([
{
$match: { _id: ObjectId("5cb14fd7db537905c89e0a72") }
},
{
$group: {
_id: null,
friends: { $push: "$friends.user.id" }
}
}
])
MongoDB Result
{
"_id" : null,
"friends" : [
[
ObjectId("5cb18680aa024b2d441f93cc"),
ObjectId("5cb18680aa024b2d441f93cd"),
ObjectId("5cb18680aa024b2d441f93ce")
]
]
}
NodeJS Query
let query = [
{
$match: { _id: user_id } // user_id = "5cb14fd7db537905c89e0a72"
},
{
$group: {
_id: null,
friends: { $push: "$friends.user.id" }
}
}
];
User.aggregate(query, (error, result) => {
console.log(result);
});
NodeJS Result
[]