gpt4 book ai didi

javascript - Node.js:mongoose .populate() 未显示数据

转载 作者:行者123 更新时间:2023-12-01 00:30:51 25 4
gpt4 key购买 nike

我正在尝试显示数据库中的数据。我有 3 个架构,将它们全部合并为一个。但是,合并数据并未显示。我已附上我的 3 个架构。

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

图书 Controller :

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

索引.pug:

ul
each book in bookList
li
a(href=book.url) #{book.title}
| (#{book.author.name})

else
li No book Has Been Listed Yet...!
  1. 网址未附加 ID
  2. 未显示作者数据
  3. 如果我使用.populate(),那么。它正在显示(Nan)
  4. 如果我不使用 populate,它不会返回任何内容

预期输出: apes and angels (约翰)

当前输出: apes and angels (南)

最佳答案

请尝试以下代码。我想,它会起作用

exports.bookList = async(req, res, next) => {
try {
const bookList = await Book.find({}).populate('author').exec((error, list) => list);

res.render('./book/index', { title: 'Book List', bookList: bookList});
} catch (error) {
res.status(500).json({ message: error.message });
}
};

关于javascript - Node.js:mongoose .populate() 未显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58552311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com