Home > front end >  Display data from another collection in MongoDB
Display data from another collection in MongoDB

Time:07-25

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 });
  }
};

CodePudding user response:

Try this:

  • Transform the id string from params to a ObjectId:
let postObjectId = mongoose.Types.ObjectId(req.params.id);
  • Query using the variable defined above:
let comments = await Comment.find({ postId: postObjectId});

CodePudding user response:

Use lookup in an aggregation query. please refer to this link.

https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/

example: db.post.aggregate([{ $lookup: { From: ‘comment’, LocalField: ‘user_id’, foreignField: ‘user_id’, as: ‘whatever_name_you_want’ }}]);

  • Related