javascript - 只从 mongoose.find 返回 _id
问题描述
想要获取所有用户但只返回 _ids 列表,检查数据库中保存的数据一切似乎都很好。
这是用户模型
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"
},
]
解决方案
不要同时使用 .then 和 await 。试试这个。假设模型是正确的。
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}`,
});
}
}
}
推荐阅读
- python - 停用词与 sklearn CountVectorizer 中的预处理不一致
- css - 样式化组件:如果子级具有属性,则样式化父级
- java - 如何获取 jar 外部文件的 Url?
- f# - 计算记录类型的成员
- python - 如何计算 Pandas 的收入增长?
- reactjs - 用 Jest 模拟 React-Redux 商店
- php - 每次下 Woocommerce 订单时,如何从插件中调用 PHP 函数?
- html - 根据图片相应地调整此 Paypal 的徽标和文字
- powerbi - 页面级筛选器的 Power BI 异常
- r - dplyr:使用 mutate() 创建具有复杂操作的新列