首页 > 解决方案 > 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 个完整记录?我该如何解决这个问题?

谢谢|

标签: javascriptnode.jsmongodbmongoose

解决方案


将 res.json(...) 更改为基本上是箭头功能的简写,它将起作用。


推荐阅读