Hi I am trying to build a social app where user can follow each other my user schema looks like this :
{
_id: ObjectId('62b6a1ad5bb65d5a1e2c0dcc'),
name: 'Admin',
username: 'Admin',
email: '[email protected]',
password: '$2b$10$qVWp8HZdId/cjVOXwiNLyeyv0jNo7BMFqFEKwNQniusazABp6s216',
profilePicture: '',
coverPicture: '',
followers: [
ObjectId('62b6abc96e3985aa5b2848b8'),
ObjectId('62b6abb96e3985aa5b2848b0'),
ObjectId('62b6abbf6e3985aa5b2848b2'),
],
following: [],
isAdmin: false,
createdAt: 2022-06-25T05:48:29.095Z,
updatedAt: 2022-06-25T07:45:33.290Z,
__v: 0,
}
Post schema
{
_id: ObjectId('62b6eaba03ca17b3eb642e24'),
userId: ObjectId('62b6a1ad5bb65d5a1e2c0dcc'),
description: 'one',
image:'https://firebasestorage.googleapis.com/v0......',
tags: [],
likes: [],
createdAt: '2022-06-25T11:00:10.108Z',
updatedAt: '2022-06-25T11:00:10.108Z',
__v: 0,
}
Followers , Following , likes are the array of objectId . I want to fetch timeline post for user it include the post of that users and post of his following . How I can achive this result without runinng loops in the nodejs server .
CodePudding user response:
use $lookup
for get matched post
the result will be added to field my-post and follow-post
try playground
db.user.aggregate(
[{
$lookup: {
from: 'post',
localField: '_id',
foreignField: 'userId',
as: 'my-post'
}
}, {
$lookup: {
from: 'post',
localField: 'followers',
foreignField: 'userId',
as: 'follow-post'
}
}]
)