Why does Express.js populate method fail in this application?

吃可爱长大的小学妹 提交于 2020-04-18 03:56:02

问题


I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.

I have Posts and Post Categories, each in its own collection.

The Categories Schema:

const mongoose = require('mongoose');

const categorySchema = new mongoose.Schema({
    cat_name: {
        type: String,
        required: true
    },
    updated_at: {
        type: Date,
        default: Date.now()
    },
    created_at: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('Category', categorySchema);

The Posts schema:

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    short_description: {
        type: String,
        required: true
    },
    full_text: {
        type: String,
        required: true
    },
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'category'
    },
    post_image: {
        type: String,
        required: false
    },
    updated_at: {
        type: Date,
        default: Date.now()
    },
    created_at: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('Post', postSchema);

The controller method that displays the posts:

exports.displayDashboard = (req, res, next) => {
    const posts = Post.find({}, (err, posts) => {
        if(err){
            console.log('Error: ', err);
        } else {
            res.render('admin/index', {
              layout: 'admin/layout',
              website_name: 'MEAN Blog',
              page_heading: 'Dashboard',
              posts: posts
            });
        }
    }).populate({ path: 'category', model: Category })
};

If in the view I have:

<table class="table table-striped table-sm mb-0">
    <thead>
        <tr class="d-flex">
            <th class="col-1 pl-2">#</th>
            <th class="col-2">Title</th>
            <th class="col-2">Category</th>
            <th class="col-2">Created</th>
            <th class="col-2">Updated</th>
            <th class="col-3 pr-2 text-right">Actions</th>
        </tr>
    </thead>
    <tbody>
        <% if (posts) { %>
            <% posts.forEach(function(post, index) { %>
                <tr data-id="<%= post._id %>" class="d-flex">
                    <td class="col-1 pl-2">
                        <%= index + 1 %>
                    </td>
                    <td class="col-2">
                        <a href="/<%= post._id %>" class="text-dark">
                            <%= post.title %>
                        </a>
                    </td>
                    <td class="col-2">
                        <%= post.category %>
                    </td>
                    <td class="col-2">
                        <%= post.created_at.toDateString(); %>
                    </td>
                    <td class="col-2">
                        <%= post.updated_at.toDateString(); %>
                    </td>
                    <td class="col-3 text-right pr-2">
                        <div class="btn-group">
                            <a href="../dashboard/post/edit/<%= post._id %>" class="btn btn-sm btn-success">Edit</a>
                            <a href="#" class="btn btn-sm btn-danger delete-post" data-id="<%= post._id %>">Delete</a>
                        </div>
                    </td>
                </tr>
                <% }); %>
                <% } else { %>
                  <tr>
                    <td colspan="5">There are no posts</td>
                   </tr>
                <% } %>
    </tbody>
</table>

an object is displayed in The Category column (of the posts table):

Yet, ig I try to display the category name using <%= post.category.cat_name %> I get this error:

Cannot read property 'cat_name' of null

What am I doing wrong?


回答1:


Use async/await operators, since populate returns a Query, which can be awaited. More informations and code examples can be found in the official Mongoose's documentation.

async function yourAwesomeFunction (req, res, next) {
   try {
      const posts = await Post
         .find({ })
         .populate({ path: 'category' });

      res.render('path/to/layout', { posts: posts });
   } catch (e) {
      // TODO: handle possible errors...
   }
};



回答2:


You Can Follow This Code

Your Model Name is: Category

// Please Define post Schema
category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
    }

// Your Controller
exports.displayDashboard =async (req, res, next) => {
    const posts =await Post.find().populate('category')
    if(posts){
      res.render('admin/index', {
              layout: 'admin/layout',
              website_name: 'MEAN Blog',
              page_heading: 'Dashboard',
              posts: posts
            })
}
}



回答3:


I found out what the problem was: I had deleted a category previously assigned to a post. The fix is simple (in the view):

<%= post.category != null ? post.category.cat_name : 'No category assigned' %>

instead of

<%= post.category.cat_name %>

Many thanks to everyone that got involved for the help.



来源:https://stackoverflow.com/questions/61214750/why-does-express-js-populate-method-fail-in-this-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!