Node.js:猫鼬.populate()未显示数据

时间:2019-10-25 04:43:18

标签: javascript node.js express mongoose

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

async-wait与try-catch配合良好,对我来说似乎很干净。我也尝试遵循mongoose populate。两者返回相同的结果。

需要提及:我是新手。因此,不要对遵循的最佳做法有个好主意。

Book Schema:

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...!
  1. URL未附加ID
  2. 作者数据未显示
  3. 如果我使用.populate(),那么。它显示(Nan)
  4. 如果我不使用填充,则不会返回任何内容

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

当前输出: apes and angels(NaN)

2 个答案:

答案 0 :(得分:1)

请尝试以下代码。我认为这会起作用

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

答案 1 :(得分:1)

在我的查询中,我只需要添加以下回调:

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

            // console.log(bookList);

            res.render('./book/index', { title: 'Book List', bookList: bookList});
        });

    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

主要问题是Schema中的箭头功能。我已经使用箭头功能来获取对象。但是,箭头功能不适用于对象。这里是参考:medium

相关问题