gpt4 book ai didi

javascript - mongodb : get all users

转载 作者:行者123 更新时间:2023-12-02 23:54:24 25 4
gpt4 key购买 nike

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

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);

最佳答案

使用asyncawait时不需要使用.then

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

关于javascript - mongodb : get all users,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55467051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com