首页 > 解决方案 > 从异步 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;

标签: mongodbtypescriptexpress

解决方案


我只是错过了服务中的等待

return await createdVacation.save();

推荐阅读