'lookup array shows no result
i am building an apllication with mongoose and node.js that enables you to post, comment, and like both the posts and the comments.
those are my schemas and the query that i am trying to built to send the user using the apllication all the posts, comments, likes to both the comment section and the post section.
tried to use lookup with mongoose to get comments (and to them likes),but the the pogram shows me no result as can you see:
( i checked by the way .)
comment.js
const commentSchema=
new mongoose.Schema({
userID : {type: mongoose.Types.ObjectId, ref: "User",required: true },
content : {type: String,required: true },
date :{type : Date,default:()=>Date.now()} ,
})
module.exports=mongoose.model("comment",commentSchema)
likes.js
const LikesSchema= new mongoose.Schema({
userID : {type: mongoose.Types.ObjectId, ref: "user",required: true },
postCommentID : {type: mongoose.Types.ObjectId ,required: true } //can be both a comment or a post
})
module.exports=mongoose.model("likes",LikesSchema)
posts.js
const postSchema= new mongoose.Schema({
userID : {type: mongoose.Types.ObjectId, ref: "User",required: true },
content : {type: String,required: true },
date : {type : Date,default:()=>Date.now()},
commentsID :[{type:mongoose.Types.ObjectId, ref:'comment' }],
})
module.exports=mongoose.model("post",postSchema)
incomplete query
Query.js
post.aggregate(
[
{
$lookup: {
from: 'likes',
localField: '_id',
foreignField: 'postCommentID',
as: '_likes'
},
},
{
//NOT WORKING
$lookup: {
from: 'comment',
localField : 'commentsID',
foreignField : '_id',
as: 'comments'
},
},
{
$set: {
'likes': '$_likes.userID'
}
},
{
$project: {
'_likes': 0,
}
},
]
)
result: as can you see the comment section is empty.
[{
_id: new ObjectId("621fdff521935fad17cc27b5"),
userID: new ObjectId("621ba7b84ade9cd7ebe7ef46"),
content: 'new post',
commentsID: [
new ObjectId("621fe07c21935fad17cc29f9"),
new ObjectId("621fe2b221935fad17cc2aef"),
new ObjectId("621fe2ff21935fad17cc2b45"),
new ObjectId("621fe83260288e8ee9db1d62"),
new ObjectId("621fe9361ab243a8c2ebb0eb"),
new ObjectId("621ff5d471b483d2f59ca493")
],
date: 2022-03-02T21:21:57.660Z,
__v: 0,
comments: [],
likes: [
new ObjectId("621fe07c21935fad17cc29f9"),
new ObjectId("621fe2b221935fad17cc2aef"),
new ObjectId("621fe2ff21935fad17cc2b45")
]
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
