Javascript mongodb:获取所有用户
如何编辑我的此函数以获取所有用户?我刚刚开始学习AsyncAwait,我很难学习如何获取请求体。 以下是我的功能:Javascript mongodb:获取所有用户,javascript,mongodb,typescript,Javascript,Mongodb,Typescript,如何编辑我的此函数以获取所有用户?我刚刚开始学习AsyncAwait,我很难学习如何获取请求体。 以下是我的功能: export const get: Operation = async ( req: express.Request, res: express.Response ) => { commonUtility.showRequestParam(req); let users: db.IUserDocument[] = []; try { // De
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);
您不需要使用。然后在使用async和Wait时
阅读有关async Wait的更多信息->非常感谢您的回复,我想知道如何才能仅获取id和用户名?如何过滤我的响应?使用投影操作符。查找{},{u id:1,用户名:1}。只获取我们需要的必填字段。我发布了一个新问题,我认为如果可以的话,您真的可以帮助我
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);
}
};