Mongoose exec()
method gives you a fully-fledged promise and when you return a value in the then
...exec().then(doc => {
return(doc); // <-- returns a pending promise
});
this returns a Promise in the pending status, like what you are getting currently.
There are a number of ways you can return the document. Using async/await, follow this pattern:
exports.main = async (req, res, next) => {
try {
const data = await Post.findOne({ active: true }).sort({ $natural: -1 }).exec();
console.log(data);
res.status(200).send(data);
} catch(err) {
console.error(err);
next();
}
}
Using the callback function
exports.main = (req, res, next) => {
Post.findOne({ active: true }).sort({ $natural: -1 }).exec((err, data) => {
if (err) throw err;
console.log(data);
res.status(200).send(data);
});
}
Using promises
exports.main = (req, res, next) => {
Post.findOne({ active: true }).sort({ $natural: -1 }).exec().then(data => {
console.log(data);
res.status(200).send(data);
}).catch(err => {
console.error(err);
next();
});
}