I have two separate collection in MongoDB 1-> Post, 2-> Comment.
Post-schema:
const postSchema = new mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
media: {
type: [mongoose.Schema.Types.Mixed],
trim: true,
required: true,
},
text: String,
mentions: {
type: Array,
default: [],
},
hashTags: {
type: ["String"],
},
likes: {
type: Array,
default: [],
},
postStatus: {
type: "String",
default: "public",
enum: ["public", "private"],
},
deletedAt: {
type: "Date",
default: null,
},
},
{ timestamps: true }
);
comment schema:
const commentSchema = new mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
postId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
required: true,
},
commentText: String,
},
{ timestamps: true }
);
Now I want to display all the comments of requested post. Post table does not have anything that links to Comment that is why I can not use populate(). but Comment table have postId to connect.
Here’s what I have tried:
exports.getPostById = async (req, res) => {
try {
let post = await Post.findById(req.params.id);
if (!post) return res.status(404).json({ message: "No Post found" });
let comment = await Comment.find({ postId: { $in: {post: req.params.id} } });//Wrong query
return res.status(200).send(post);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
2
Answers
Try this:
ObjectId
:Use lookup in an aggregation query.
please refer to this link.
https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/
example: