当前位置: 首页 > 知识库问答 >
问题:

Express:在控制器中使用异步等待的问题

包承望
2023-03-14
const Employee = require('../models/employee');

const employeeCtrl = {};

employeeCtrl.getEmployees = async (req, res) => {
  const employees = await Employee.find();
  res.json(employees);
}

employeeCtrl.createEmployee = async (req,res) => {
  const employee = new Employee(req.body)
  console.log(employee);
  await employee.save();
  res.json('recivied');
}

employeeCtrl.getEmployee = function() {

}

employeeCtrl.editEmployee = function() {

}

employeeCtrl.deleteEmployee = function() {

}

module.exports = employeeCtrl;

为什么find不是函数

这是模型:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const EmployeeSchema = new Schema({
  name: {type: String, required: true},
  position: {type: String, required: true},
  office: {type: String, required: true},
  salary: {type: Number, required: true}
})

mongoose.model('Employee', EmployeeSchema);

共有1个答案

齐振
2023-03-14

您没有从模型中导出任何东西。您需要像这样导出它:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const EmployeeSchema = new Schema({
  name: {type: String, required: true},
  position: {type: String, required: true},
  office: {type: String, required: true},
  salary: {type: Number, required: true}
})

module.exports = mongoose.model('Employee', EmployeeSchema);

此外,.find()不返回promise。它返回一个query对象,如文档中所述:https://mongoosejs.com/docs/api.html#model_model.find

您需要用.exec()链接它,后者返回promise:https://mongoosejs.com/docs/api.html#query_query-exec

employeeCtrl.getEmployees = async (req, res) => {
  const employees = await Employee.find().exec();
  res.json(employees);
}
 类似资料:
  • 我有这个简单的例子给我的控制器,并没有像预期的那样工作 输出:开始、结束、中间 期望:开始、中间、结束

  • 问题内容: 我有两个MVC网站。站点1的控制器使用以下代码调用站点2 我可以直接浏览URL并查看JSON。但是从MVC中的对等网站下载JSON的正确方法是什么? 问题答案: 你或许应该把控制器方法为方法和用途,以避免死锁。 Microsoft的ASP.NET教程包括有关ASP.NET MVC 4中异步方法 的页面。

  • 我想进行一个基于当前状态的API调用,但不能使setState函数作为异步函数工作。 给我错误: 类型为“”的参数(状态:只读)= 如果我在setState方法之外获取数据,它会起作用,但我害怕对过时的页码进行API调用:

  • 我需要在函数中运行各种步骤,但步骤必须按特定顺序运行。我尝试实现一个函数,如下所示: 控制台中的预期结果应该是1,2,3,但我得到了3,2,1。似乎忽略了参数。 编辑功能在上面的示例中仅用于模拟繁重的任务。在我的项目中,我不会使用它。事实上,我需要连接到一个数据库,然后在进入下一步之前重新格式化结果。即使包括,2也会在1之前登录。换句话说,空列表被传递到我的图形,因为没有考虑。以下是我当前的代码:

  • 问题内容: 我认为节点7.4支持异步/等待,但是此示例不起作用: 结果是: 如何在节点7.4上使用异步/等待? 问题答案: 是的,Node.js v7支持async-await,但将其锁定在标志后面。尚未准备就绪的功能不在此标记后面。 要在Node.js v7中使用async-await,只需使用此标志运行Node服务- async-await的正式发行版预定于4月启动的Node.js v8。 您

  • 我以为async/wait在节点7.4中得到了支持,但是这个例子不起作用: 结果: 如何在node 7.4中使用async/await?