'node.js mongoose null results being returned
I'm using node.js and mongoose. In my router I have
const books = await BookService.recentRest();
res.json({ find: books });
});
and my recentRest function is
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;
};
'Book' is
const BookService = require('./bookTitle.service');
module.exports = BookService(Book);
The problem I have is that 'details' is null and seems to be returned before the code is complete. I'm getting the correct results for 'books' and building up 'detail' seems ok. Obviously something is wrong with my async and await uses but I can't see what that is. Any help greatly appreciated.
Solution 1:[1]
Someone (sorry I don't have the id) suggested I rewrite the code but this answer has disappeared! The suggestion was
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;
};
This didn't work as book.title etc. were showing undefined. After a bit more research I just had to change
for(const book in books)
to
for(const book of books)
and it works! I'd like to thank the person who gave the answer that has since disappeared.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3017691 |
