javascript Node. js/ Mongoose -尝试创建包含数组的文档时出错,尽管我的代码与讲师的代码相同

von4xj4u  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(78)
    • 我的 Mongoose 模式是:**
const tourSchema = new mongoose.Schema({
...
images: [String],
...
startDates: [Date]
});
    • 我的API创建函数是:**
exports.createTour = async (req, res) => {
  try {
    const newTour = await Tour.create(req.body);
    res.status(201).json({
      status: "success",
      data: {
        tour: newTour
      }
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      message: error
    });
  }
};
    • 数据输入:**
{
    "name": "The Forest Hiker",
    ...
    "images": ["tour-1-1.jpg", "tour-1-2.jpg", "tour-1-3.jpg"],
    "startDates": ["2021-04-25,10:00", "2021-07-20,10:00", "2021-10-05,10:00"]
}
    • 错误:**
{
    "status": "fail",
    "message": {
        "errors": {
            "images": {
                "stringValue": "\"[]\"",
                "valueType": "string",
                "kind": "[undefined]",
                "value": "[]",
                "path": "images.1",
                "reason": {},
                "name": "CastError",
                "message": "Cast to [undefined] failed for value \"[]\" (type string) at path \"images.1\" because of \"TypeError\""
            },
            "startDates": {
                "stringValue": "\"[]\"",
                "valueType": "string",
                "kind": "[undefined]",
                "value": "[]",
                "path": "startDates.1",
                "reason": {},
                "name": "CastError",
                "message": "Cast to [undefined] failed for value \"[]\" (type string) at path \"startDates.1\" because of \"TypeError\""
            },
            "images.undefined": {
                "stringValue": "\"[\"tour-3-1.jpg\",\"tour-3-2.jpg\",\"tour-3-3.jpg\"]\"",
                "valueType": "string",
                "kind": "[undefined]",
                "value": "[\"tour-3-1.jpg\",\"tour-3-2.jpg\",\"tour-3-3.jpg\"]",
                "path": "images.undefined",
                "reason": {},
                "name": "CastError",
                "message": "Cast to [undefined] failed for value \"[\"tour-3-1.jpg\",\"tour-3-2.jpg\",\"tour-3-3.jpg\"]\" (type string) at path \"images.undefined\" because of \"TypeError\""
            },
            "startDates.undefined": {
                "stringValue": "\"[\"2022-01-05,10:00\",\"2022-02-12,10:00\",\"2023-01-06,10:00\"]\"",
                "valueType": "string",
                "kind": "[undefined]",
                "value": "[\"2022-01-05,10:00\",\"2022-02-12,10:00\",\"2023-01-06,10:00\"]",
                "path": "startDates.undefined",
                "reason": {},
                "name": "CastError",
                "message": "Cast to [undefined] failed for value \"[\"2022-01-05,10:00\",\"2022-02-12,10:00\",\"2023-01-06,10:00\"]\" (type string) at path \"startDates.undefined\" because of \"TypeError\""
            }
        },
        "_message": "Tour validation failed",
        "name": "ValidationError",
        "message": "Tour validation failed: images: Cast to [undefined] failed for value \"[]\" (type string) at path \"images.1\" because of \"TypeError\", startDates: Cast to [undefined] failed for value \"[]\" (type string) at path \"startDates.1\" because of \"TypeError\", images.undefined: Cast to [undefined] failed for value \"[\"tour-3-1.jpg\",\"tour-3-2.jpg\",\"tour-3-3.jpg\"]\" (type string) at path \"images.undefined\" because of \"TypeError\", startDates.undefined: Cast to [undefined] failed for value \"[\"2022-01-05,10:00\",\"2022-02-12,10:00\",\"2023-01-06,10:00\"]\" (type string) at path \"startDates.undefined\" because of \"TypeError\""
    }
}
    • 软件版本:** 节点v19.5.0 Mongoose 6.9.0版 mongodb(在Atlas共享集群上)v6.0.4

备注

我正在连接到Atlas共享集群。我必须使用mongoose v6.9.0,v5.x.x抛出了一个URI解析错误,除了更新mongoose之外,我无法解决该错误。(本地连接正常,从Mongo Shell连接到集群也正常。)
我在代码中使用省略号(...)的地方与我正在学习的Udemy课程中的代码片段完全相同,它对教师有效,似乎对其他所有人也有效。

我的想法

我怀疑我正在使用的较新的Mongoose版本,或者一些配置设置,因为我的代码与Jonas编写的代码100%相同。我已经花了2个小时试图弄清楚这一点,但无济于事。最后,我决定做一个变通方案。

我的解决方案

当我将数组作为字符串传递时,一切都很好,我只需要在以后每次使用它们时转换回来,这对性能不好。Schema:

const tourSchema = new mongoose.Schema({
...
images: String,
...
startDates: String
});

API创建函数:

exports.createTour = async (req, res) => {
  try {
    req.body.images = req.body.images.toString();
    req.body.startDates = req.body.startDates.toString();
    const newTour = await Tour.create(req.body);
    res.status(201).json({
      status: "success",
      data: {
        tour: newTour
      }
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      message: error
    });
  }
};
    • 欢迎您提供任何帮助或反馈!**
    • 编辑/增编1**

发送到服务器的req.body是以下JSON对象:

{
    "name": "The Snow Adventurer",
    "duration": 4,
    "maxGroupSize": 10,
    "difficulty": "difficult",
    "ratingsAverage": 4.5,
    "ratingsQuantity": 13,
    "price": 997,
    "summary": "Exciting adventure in the snow with snowboarding and skiing",
    "description": "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua, ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum!\nDolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur, exercitation ullamco laboris nisi ut aliquip. Lorem ipsum dolor sit amet, consectetur adipisicing elit!",
    "imageCover": "tour-3-cover.jpg",
    "images": ["tour-3-1.jpg", "tour-3-2.jpg", "tour-3-3.jpg"],
    "startDates": ["2022-01-05,10:00", "2022-02-12,10:00", "2023-01-06,10:00"]
  }

console. log(req. body)是在创建新文档之前直接记录的-req. body,如下所示:

exports.createTour = async (req, res) => {
  try {

    console.log(req.body);

    console.log(req.body.images);
    console.log("The type of req.body.images is: ", typeof req.body.images);

    console.log(req.body.startDates);
    console.log(
      "The type of req.body.startDates is: ",
      typeof req.body.startDates
    );

    const newTour = await Tour.create(req.body);
    res.status(201).json({
      status: "success",
      data: {
        tour: newTour
      }
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      message: error
    });
  }
};
{
  name: 'The Snow Adventurer',
  duration: 4,
  maxGroupSize: 10,
  difficulty: 'difficult',
  ratingsAverage: 4.5,
  ratingsQuantity: 13,
  price: 997,
  summary: 'Exciting adventure in the snow with snowboarding and skiing',
  description: 'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua, ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum!\n' +
    'Dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur, exercitation ullamco laboris nisi ut aliquip. Lorem ipsum dolor sit amet, consectetur adipisicing elit!',
  imageCover: 'tour-3-cover.jpg',
  images: [ 'tour-3-1.jpg', 'tour-3-2.jpg', 'tour-3-3.jpg' ],
  startDates: [ '2022-01-05,10:00', '2022-02-12,10:00', '2023-01-06,10:00' ]
}

有趣的是,req.body显示数组正在被传递给Tour.create()方法,而且我还为传递的数组创建了typeof日志,它返回以下内容:

[ 'tour-3-1.jpg', 'tour-3-2.jpg', 'tour-3-3.jpg' ]
The type of req.body.images is:  object
[ '2022-01-05,10:00', '2022-02-12,10:00', '2023-01-06,10:00' ]
The type of req.body.startDates is:  object

这让我确信这些字段是Array对象--通过推理推断出字符串是JS中的一个基元类型,因此typeof不能返回object,这使得这个bug变得更加奇怪。

kupeojn6

kupeojn61#

您是否使用Postman来测试您的API?您的代码看起来运行良好,Schemareq.body没有问题,我唯一认为的是您错误地配置了Postman,因此它将您的请求作为string发送,而不是作为array发送。请确保将Postman中的内容类型设置为JSON,如this image所示

相关问题