javascript - Mongoose:当使用“toObject”时,res.json 返回带有空记录的数组。为什么以及如何解决这个问题?
问题描述
我目前正在尝试设置一个 API,我可以在其中获取分配给 userId 的对象数组。我已经定义了以下猫鼬模型:
const userSchema = mongoose.Schema({
name: { type: String, required: true, trim: true },
email: { type: String, required: true, unique: true, trim: true },
password: { type: String, required: true, minlength: 6 },
engagements: [
{ type: mongoose.Types.ObjectId, required: true, ref: "Engagement" },
],
});
并设置了这样的控制器:
exports.getEngsByUid = async (req, res, next) => {
const uid = req.params.uid;
let uidWithEngs;
try {
uidWithEngs = await User.findById(uid).populate("engagements");
} catch (err) {
const error = new HttpError("Fetching engagements failed!", 500);
return next(error);
}
if (!uidWithEngs || uidWithEngs.engagements.length === 0) {
return next(new HttpError("Could not find engagements for this user", 500));
}
res.json({
engagements: uidWithEngs.engagements.map((e) => {
e.toObject();
}),
});
};
我目前面临的问题是,当我向我定义的路径发送 GET 请求时,我获取了一个具有空值的“参与”数组:
{
"engagements": [
null,
null
]
}
但是,如果我删除 toObject 方法(和所需的 .map 方法)并按如下方式设置 res :
res.json({
engagements: uidWithEngs.engagements,
});
我确实得到了我的数组:
{
"engagements": [
{
"_id": "5fb47975eb319d24c098a06d",
"title": "testTitle1",
"client": "testClient1",
"year": 2030,
"owner": "5fb4795deb319d24c098a06b",
"__v": 0
},
{
"_id": "5fb4698aeb319d24c098a06f",
"title": "testTitle2",
"client": "testclient2",
"year": 2040,
"owner": "5fb4795deb319d24c098a06b",
"__v": 0
}
]
}
为什么使用 toObject() 会返回一个包含 2 个空记录的数组,而当我不使用 toObject() 方法时,它会返回 2 个完整记录?我该如何解决这个问题?
谢谢|
解决方案
将 res.json(...) 更改为基本上是箭头功能的简写,它将起作用。
推荐阅读
- c# - 导出加密的 XML 文件并在另一个应用程序中解密?
- excel - Excel VBA For 循环与 UsedRange 计数错误
- javascript - 如何让我的程序读取输入转义序列
- php - 关于 PHP 中关联数组的一些查询
- javascript - 如何使用“@react-google-maps/api”绘制虚线多边形和圆形?
- javascript - 如何使用纯javascript将字符串保存在剪贴板中?
- lua - 如何在 LOVE2D 中绘制四边形图像?
- flutter - FlutterError (setState() 在 dispose() 之后调用:(生命周期状态:已失效,未挂载)
- sql - 如何通过在 Hive SQL 中的列中分布来制作一种列
- plotly - Plotly-Dash:如何使用 dash 引导组件设计布局?