mongodb - 从异步 mongo.save() 获取空对象
问题描述
我已将我的代码分成一个控制器和一个数据库服务,并添加到 async/await 中以确保我从 mongo.db 返回 json 响应。不幸的是,它一直在发送一个空对象 {}。为什么我的 await 什么都不做,它只是发回一个空对象。应用于数据数组的简单查找的相同代码返回完整的模拟对象。
控制器
const postVacation = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
const vacation: IVacation = {
id: undefined,
name: req.body.name,
description: req.body.description,
};
try {
const newVacation = await vacationData.addVacation(vacation);
res.status(201).json(newVacation);
} catch (error) {
next(new HttpException(500, error.toString()));
}
};
服务
const addVacation = async (vacation: IVacation): Promise<IVacationMongo> => {
const createdVacation = new Vacation({
name: vacation.name,
description: vacation.description,
});
return createdVacation.save();
};
楷模
import mongoose from "mongoose";
const Schema = mongoose.Schema;
export interface IVacation {
id: string;
name: string;
description: string;
}
export interface IVacationMongo extends mongoose.Document {
name: string;
description: string;
}
const vacationSchema = new Schema({
name: { type: String, required: true },
description: { type: String, required: true },
});
const Vacation = mongoose.model<IVacationMongo>("Vacation", vacationSchema);
export default Vacation;
解决方案
我只是错过了服务中的等待
return await createdVacation.save();
推荐阅读
- javascript - 使用导入时如何延迟加载css
- oop - 使两个类的对象互为成员是一种不好的做法吗?
- node.js - AWS ElasticBeanstalk NodeJS - 502 错误:recv() 在从上游读取响应标头时失败(104:对等方重置连接)
- android - Android中的暂停和恢复处理程序
- python - 用平均值减去当前像素时如何处理负值
- javascript - 无法下载在 javascript 中的文件名中包含特殊字符的文件
- python - Bitmex 签名无效
- c# - 如何添加不会保留的其他导航属性?
- javascript - 在 React Native Picker 中选择第一个项目时,有没有办法调用方法?
- python-3.x - 如何使用python删除列表中的括号和单个婴儿床