This works as expected:
let responses = await Response.find({
responder_id: req.user._id,
}).populate({ path: "query_id", select: ["query_type", "content"] });
responses = responses.map((response) => {
return response.query_id;
});
But the below does not:
let responses = await Response.find({
responder_id: req.user._id,
})
.populate({ path: "query_id", select: ["query_type", "content"] })
.map((response) => {
return response.query_id;
});
The only thing that I can think of is maybe it has something to do with the asynchronous nature of these functions.
Priority is not as you think it is. What is being awaited is not Response.find(...)
, but Response.find(...).populate(...)
. With this in mind, here's the way to write it in the second form correctly (with the only difference being a pair of parentheses):
let responses = (await Response.find({
responder_id: req.user._id,
})
.populate({ path: "query_id", select: ["query_type", "content"] }))
.map((response) => {
return response.query_id;
});
However, some re-indenting would be needed to make this readable. The first snippet might be easier to read anyway.