Home > Blockchain >  How to get a certain field of an embedded MongoDB document knowing its ObjectId
How to get a certain field of an embedded MongoDB document knowing its ObjectId

Time:10-08

I have two collections in MongoDB database, Post and User. Each post contains the creator's ObjectId. When fetching all posts from the database, I want to add the name information, which is a field of User/creator. I tried to access the name field by post.creator.name, but it is not working.

const postSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    category: {
      type: String,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
    imageUrl: {
      type: String,
      required: true,
    },
    creator: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
  },
  { timestamps: true }
);

const userSchema = new Schema({
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  status: {
    type: String,
    required: true,
  },
  isExpert: {
    type: Boolean,
    required: true,
  },
  posts: [
    {
      type: Schema.Types.ObjectId,
      ref: "Post",
    },
  ],
});

exports.getPosts = (req, res, next) => {
  Post.find({}).then((posts) => {
    const postsWithAuthorName = posts.map(post => {
      return {
        ...post,
        name: post.creator.name
      }
    })
    res.status(200).json({
      posts: postsWithAuthorName,
    });
  });
};

CodePudding user response:

Try this

Post.find({}).populate('creator', 'name')

See populate doc for reference.

When you query posts, creator is just an ObjectId, so you can't just call .name on it. To make it work you need to lookup this data by using e.g. populate.

  • Related