【问题标题】:node.js mongoose null results being returned返回 node.js mongoose null 结果
【发布时间】:2022-02-16 20:04:34
【问题描述】:

我正在使用 node.js 和猫鼬。在我的路由器中,我有

    const books = await BookService.recentRest();
    res.json({ find: books });
  });

而我的 recentRest 函数是

const recentRest = (Book) => async () => {
  const books = await Book.find({}, "-_id title author return_date")
    .sort({ return_date: -1, title: -1 })
    .limit(10)
    .exec();
  let details = [];
  let detail = new Object();
  await Object.values(books).forEach(async (book) => {
    detail.title = book.title;
    detail.returnDate = book.return_date;
    detail.author_id = book.author;
    const Author = require("../models/author.model");
    const authorName = await Author.findOne({ _id: book.author }, "first last");
    detail.author = authorName.first + " " + authorName.last;
    details.push(detail);
  });
  return details;
};

“书”是

const BookService = require('./bookTitle.service');
module.exports = BookService(Book);

我遇到的问题是“详细信息”为空,并且似乎在代码完成之前返回。我得到了“书籍”的正确结果,建立“细节”似乎还可以。显然我的 async 和 await 使用出了点问题,但我看不出那是什么。非常感谢任何帮助。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    有人(对不起,我没有身份证)建议我重写代码,但这个答案已经消失了!建议是

      const books = await Book.find({}, "-_id title author return_date")
        .sort({ return_date: -1, title: -1 })
        .limit(10)
        .exec();
      let details = [];
        for (const book in books) {
          const detail = {
            title: book.title,
            returnDate: book.return_date,
            author_id: book.author,
          };
          const Author = require("../models/author.model");
          const authorName = await Author.findOne(
            { _id: book.author },
            "first last"
          );
          detail.author = authorName.first + " " + authorName.last;
          details.push(detail);
        }
        return details;
      
    };
    

    这不起作用,因为 book.title 等显示未定义。经过更多的研究,我只需要改变

    for(const book in books)
    

    for(const book of books)
    

    它有效!我要感谢给出答案的人,后来消失了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 2014-11-02
      相关资源
      最近更新 更多