【发布时间】:2020-02-21 10:33:14
【问题描述】:
我正在尝试显示数据库中的数据。我有 3 个 Schema,将它们合二为一。但是,合并的数据没有显示。我附上了我的 3 Schema。
async-wait 与 try-catch 一起工作得很好,这对我来说似乎很干净。我也尝试关注mongoose populate。两者都返回相同的结果。
需要说明:我是新手。因此,对于要遵循的最佳实践没有好主意。
图书架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: {
type : String,
required : [true, 'Book Title is Required'],
max : 100,
min : 5,
trim : true,
lowercase: true
},
author: {
type : Schema.Types.ObjectId,
ref : 'Author',
required: [true, 'Author is Required']
}
genre: [{
type: Schema.Types.ObjectId,
ref : 'Genre'
}]
}, { collection : 'book', timestamps: true });
BookSchema
.virtual('url')
.get(() => {
return 'book/' + this._id;
});
module.exports = mongoose.model('Book', BookSchema);
作者架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AuthorSchema = new Schema({
firstName: {
type : String,
required : [true, 'First Name is Required'],
max : 100,
min : 5,
trim : true,
lowercase: true
},
lastName: {
type : String,
required : [true, 'Last Name is Required'],
max : 100,
min : 5,
trim : true,
lowercase: true
}
}, { collection : 'author', timestamps: true });
AuthorSchema
.virtual('name')
.get(() => {
return this.firstName + this.lastName;
});
module.exports = mongoose.model('Author', AuthorSchema);
类型架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const GenreSchema = new Schema({
name: {
type : String,
required : [true, 'Genre Name is Required'],
max : 100,
min : 3,
trim : true,
lowercase: true
}
}, { collection : 'genre', timestamps: true });
module.exports = mongoose.model('Genre', GenreSchema);
图书控制器:
exports.bookList = async(req, res, next) => {
try {
const bookList = await Book.find({}).populate('author').exec();
res.render('./book/index', { title: 'Book List', bookList: bookList});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
index.pug:
ul
each book in bookList
li
a(href=book.url) #{book.title}
| (#{book.author.name})
else
li No book Has Been Listed Yet...!
- 网址未附加 id
- 作者数据未显示
- 如果我使用 .populate(),那么。它显示(南)
- 如果我不使用填充,它不会返回任何内容
预期输出: apes and angels(约翰)
当前输出: apes and angels(NaN)
【问题讨论】:
标签: javascript node.js express mongoose