javascript - 无法同步 Mongoose 操作以返回数组

标签 javascript node.js mongodb express mongoose

作为员工应用程序管理的一部分,我希望将业务逻辑数据库操作与我的主应用程序文件分开。 最简单的操作是使用async/await从数据库中读取所有员工进行同步:

module.exports.getEmployees = async () => {
    const employees = await Employee.find();
    return employees;
}

在我的 app.js 中,我输入了以下代码:

const employee = require(__dirname + "/models/employee.js");

app.get("/employees", (req, res) => {
    const employeeList =  employee.getEmployees();
    employeeList.then(res.send(employeeList));
})

但是数组仍然显示为空?

最佳答案

Promise 中的

then 子句接受函数作为参数,并且该函数有一个保存实际响应的参数。

类似这样的东西 -

new Promise().then((response) => {
    console.log(response);
});

您正在执行 employeeList.then(res.send(employeeList)); 这意味着 then 子句的参数是 res.send() ,这将不起作用.

试试这个 -

employeeList.then((list) => {
    // please note the response type here depends on the Content-Type set in the response Header
    res.send(list);
    // In case of normal http server, try this -
    res.send(JSON.stringify(list));
});

我希望这会有所帮助。

关于javascript - 无法同步 Mongoose 操作以返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60682560/

相关文章:

php - 将数据从关系数据库反规范化到非关系数据库的最佳实践

node.js - 跨多个模型导出和重用我的 Mongoose 连接

python - 使用 pymongo 保持连续的 mongo 连接处于事件状态

javascript - 如何使用 webpack 2 从 node_modules 导入 css

javascript - 我如何绕过 firebase 在响应时给出的数组中的随机 id?

c# - 在 C# 中运行 Javascript 的最可靠方法?

javascript - 在函数之外返回值

javascript - 在ReactJS中添加onChange后无法在输入字段中输入

node.js - 在 Linux 上使用 clasp 时缺少 node-v57-linux-x64-glibc/grpc_node.node

node.js - NodeJS、PM2、GC、Grafana - 更好地理解