'How to populate Category in Post and Show in Option in Node js

I'm trying to populate the category in Post. I'm making a CMS, where users can create/edit/delete posts and categories. I'm trying to implement a function that allows the user to choose created category while making the post. From the option. Here is some important code. Post Module

const mongoose = require("mongoose");

const PostSchema = new mongoose.Schema({
  title: {
    type: String,
    trim: true,
    required: true,
  },
  description: {
    type: String,
    trim: true,
    required: true,
  },
  status: {
    type: String,
    default: "public",
    enum: ["public", "private"],
  },
  image: String,
  createdBy: {
    type: String,
  },
  category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Category",
    require:true,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});

//! Exporting Module
module.exports = mongoose.model("Post", PostSchema);

Category Module

const mongoose = require('mongoose');

const CategorySchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true,
    unique: true,
  },
  description: {
    type: String,
    trim: true,
  }
});

//! Exporting Category Schema
module.exports = mongoose.model("Category", CategorySchema);

Post Controller

const Category = require('../model/Category');
const Post = require("../model/post");

// @ desc POST / Add New Post
exports.postNewPost = async (req, res) => {
  try {
    const cate = await Category.find();
    const post = await Post.create(req.body);
   
    req.flash("alert", {
      type: "success",
      message: "Book created successfully",
    });
    res.redirect("/posts");
  } catch (error) {
    req.flash("alert", {
      type: "danger",
      message: "Something is wrong..!",
    });
    console.log(error);
  }
};

AddPost.ejs

<form role="form" action="/posts/addpost" method="POST"
                               enctype="multipart/form-data">
// Here is other input fields like as title,description,status
// Here I want to populate category and allow user to choose
<div class="row">
                                                    <div class="input-field">
                                                        <label for="category">Choose Category</label>
                                                        <select name="category" id="category">
                                                            <% cate.forEach(cate=>{ %>
                                                                <option value="<%= cate.name %>">
                                                                    <%= cate.name %>
                                                                </option>
                                                                <% }) %>
                                                        </select>
                                                    </div>
                                                </div>
</form>

But it’s isn’t working Please help me. For reference Github repo Url : https://github.com/yajindragautam/Advance-CMS-Using-Ejs



Solution 1:[1]

If you are trying to populate category when you call the find() method, you have to call also the populate() method.

You can find how to use populate in the official documentation. Pay attention at the version of mongoose you are using, because in latest releases thepopulate() method call has changed, if you have more than one filed to populate, you can find more details in Migration guide.

In your case I think you can only add .populate('category).

const cate = await Category.find().populate('category);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Dumitru