【发布时间】:2020-06-05 20:10:55
【问题描述】:
我已将我的代码分成一个控制器和一个数据库服务,并添加到 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;
【问题讨论】:
标签: mongodb typescript express