【问题标题】:Node.js: mongoose .populate() is not showing dataNode.js:猫鼬 .populate() 未显示数据
【发布时间】: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...!
  1. 网址未附加 id
  2. 作者数据未显示
  3. 如果我使用 .populate(),那么。它显示(南)
  4. 如果我不使用填充,它不会返回任何内容

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

当前输出: apes and angels(NaN)

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 显示以下错误:无法读取未定义的属性“长度”
      • @tanjiya 你能在返回结果之前控制台.log exec 函数内的错误。像这样: exec((error, list) => {console.log(error); return list;}) 让我知道错误(如果有的话)
      • 返回 500 和 null
      • 那么,你得到的错误是 null 吗?如果是这样,您的查询正在完美执行。你可能在 res.render 中有一些错误。 500 表示内部服务器错误。它与查询无关。也请 console.log 列表参数,看看里面有什么。
      • console.log(bookList) 正在控制台中返回数据。
      猜你喜欢
      • 1970-01-01
      • 2020-11-19
      • 2019-06-24
      • 2016-02-21
      • 1970-01-01
      • 2019-05-19
      • 2019-09-16
      • 2014-01-01
      • 2012-08-12
      相关资源
      最近更新 更多