【问题标题】:Getting empty object from async mongo.save()从异步 mongo.save() 获取空对象
【发布时间】: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


    【解决方案1】:

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

    return await createdVacation.save();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 2020-06-01
      相关资源
      最近更新 更多