如何在 Node js 中的 Post 中填充类别并在选项中显示

发布于 2025-01-12 01:47:50 字数 3200 浏览 1 评论 0原文

我正在尝试填充帖子中的类别。 我正在制作一个 CMS,用户可以在其中创建/编辑/删除帖子和类别。我正在尝试实现一个功能,允许用户在发帖时选择创建的类别。从选项来看。 这是一些重要的代码。 帖子模块

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

类别模块

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

帖子控制器

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>

但它不起作用,请帮助我。 参考 Github repo Url : https://github.com/yajindragautam/Advance-CMS-使用-Ejs

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丢了幸福的猪 2025-01-19 01:47:50

如果您在调用 find() 方法时尝试填充category,则还必须调用 populate() 方法。

您可以在官方文档中找到如何使用 populate。请注意您使用的 mongoose 版本,因为在最新版本中,populate() 方法调用已更改,如果您有多个文件需要填充,您可以在 迁移指南

对于您的情况,我认为您只能添加 .populate('category)

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文