简体   繁体   中英

Display data from another collection in MongoDB

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM