冉冉說
2024-01-18 16:25:31
想要獲取所有用戶,但只返回 _ids 列表,檢查數(shù)據(jù)庫中保存的數(shù)據(jù),一切似乎都很好。這是用戶模型let UserSchema = new mongoose.Schema({ firstName: { type: String, minlength: 3, trim: true, }, lastName: { type: String, minlength: 3, trim: true, }, biography: { type: String, minlength: 5, trim: true, }, }); UserSchema.methods.toJSON = function () { let user = this; let userObject = user.toObject(); return _.pick(userObject, ["_id", "firstName", "email"]); };這是我的控制器功能const controller = { fetchUsers :async (_req, res) => { try { await User.find({}) .then((users) => { res.status(200).send(users); }) .catch((err) => { res.status(400).send(err); }); } catch (error) { res.status(400).json({ Error: `something is wrong. ${error}`, }); } }}我在郵遞員中測試的結果是:[ { "_id": "5fe26ba0d290a216c0fe6d5d" }, { "_id": "5fe26c8e40ca9a06b8c96259" }, ]
2 回答

炎炎設計
TA貢獻1808條經驗 獲得超4個贊
問題是UserSchema.methods.toJSON
方法沒有任何電子郵件字段,如果我們想過濾輸出數(shù)據(jù),最好通過mongoose.find({"condition"},{"fields"})

素胚勾勒不出你
TA貢獻1827條經驗 獲得超9個贊
不要同時使用 .then 和 wait 。嘗試一次。假設模型是正確的。
const controller = {
fetchUsers :async (_req, res) => {
try {
const users=await User.find({}).exec()
if(users){
res.status(200).send(users);
}
else{
res.status(404).send("no user found");
};
} catch (error) {
res.status(500).json({
Error: `something is wrong. ${error}`,
});
}
}
}
添加回答
舉報
0/150
提交
取消