为什么 MongoDB 填充方法在此应用程序中失败?
Why does MongoDB populate method fail in this application?
我正在研究 blogging application (click the link to see the GitHub repo) with Express, EJS 和 MongoDB。
我有 Posts 和 Post 类别,每个类别都在自己的集合中。
类别架构:
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);
Posts 架构:
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);
显示帖子的控制器方法:
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 })
};
如果在视图中我有:
<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>
对象显示在 类别 列(帖子 table 中):
然而,我尝试使用 <%= post.category.cat_name %>
显示 类别名称 我收到此错误:
Cannot read property 'cat_name' of null
我做错了什么?
使用 async/await 运算符,因为 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...
}
};
您可以遵循此代码
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
})
}
}
我发现了问题所在:我删除了 之前分配给 的类别 post。修复很简单(在视图中):
<%= post.category != null ? post.category.cat_name : 'No category assigned' %>
而不是
<%= post.category.cat_name %>
非常感谢所有参与帮助的人。
我正在研究 blogging application (click the link to see the GitHub repo) with Express, EJS 和 MongoDB。
我有 Posts 和 Post 类别,每个类别都在自己的集合中。
类别架构:
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);
Posts 架构:
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);
显示帖子的控制器方法:
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 })
};
如果在视图中我有:
<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>
对象显示在 类别 列(帖子 table 中):
然而,我尝试使用 <%= post.category.cat_name %>
显示 类别名称 我收到此错误:
Cannot read property 'cat_name' of null
我做错了什么?
使用 async/await 运算符,因为 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...
}
};
您可以遵循此代码
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
})
}
}
我发现了问题所在:我删除了 之前分配给 的类别 post。修复很简单(在视图中):
<%= post.category != null ? post.category.cat_name : 'No category assigned' %>
而不是
<%= post.category.cat_name %>
非常感谢所有参与帮助的人。