我在MongoDB中有兩個(gè)單獨(dú)的集合1->帖子,2->評(píng)論。
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 }
);
現(xiàn)在我想顯示請(qǐng)求帖子的所有評(píng)論。Post表沒有任何鏈接到注釋的內(nèi)容,這就是為什么我不能使用populate()。但評(píng)論表已發(fā)布連接。
以下是我嘗試過的:
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 });
}
};
在聚合查詢中使用查找。請(qǐng)參閱此鏈接。
https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/
示例:db.post.aggregate([{$lookup:{From:‘comment’,LocalField:‘user_id’,foreignField:‘user_id’,as:‘whatever_name_you_want’}}];