mongodb:获取所有用户

萨尔玛·扎格鲁

我如何编辑我的这个功能以获取所有用户?我刚刚开始学习异步等待,我很难学习如何获取请求正文。这是我的功能:

export const get: Operation = async (
  req: express.Request,
  res: express.Response
) => {
  commonUtility.showRequestParam(req);


  let users: db.IUserDocument[] = [];
  try {
    // Describe data acquisition and registration from mongoDB here.
    users = await UserModel.find()
      .then(data => {
        return data;
      })
      .catch(err => {
        throw err;
      });
  } catch (err) {
    // Error.
    api.responseError(res, err);
  }

  if (users.length < 1) {
    // this case is 404 ???
    api.responseJSON(res, 200, []);
  }
};

这是我的用户模型:

export const usersSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  BaseFields
});

export const UserModel = mongoose.model<db.IUserDocument>('Users', usersSchema);
阿莫尔·B·贾姆卡尔

使用.then不需要使用asyncawait

export const get: Operation = async (
  req: express.Request,
  res: express.Response
) => {
  commonUtility.showRequestParam(req);
  let users: db.IUserDocument[] = [];
  try {
    users = await UserModel.find();
    api.responseJSON(res, 200,users);
  } catch (err) {
    // Error.
    api.responseError(res, err);
  }  
};

在此处阅读有关异步等待的更多信息 -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章