0

我正在尝试向 mongo db 发出测试发布请求。在邮递员中,我收到此错误:

{
    "success": false,
    "message": "Post validation failed: photo: Path `photo` is required., body: Path `body` is required., snippet: Path `snippet` is required., title: Path `title` is required."
}

这就是我在邮递员中所拥有的。

这是邮递员的截图。

const postSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    snippet: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    photo: {
        type: String,
        required: true
    },
}, { timestamps: true });

const Post = mongoose.model('Post', postSchema);
module.exports = Post;

这是我的架构。

router.post("/add-story", upload.array('photo', 10), async(req, res) => {
  try{
    let post = new Post();
    Post.title = req.body.title;
    Post.description = req.body.description;
    Post.photo = req.body.photo;
    Post.snippet = req.body.snippet;

    await post.save();

    res.json({
      status: true,
      message: "Successfully saved."
    });
  } catch(err) {
    res.status(500).json({
      success: false,
      message: err.message
    });
  }
});

这是 POST 请求。

我尝试关闭“required:true”,请求成功通过并在我的数据库中创建了一个空条目。

4

3 回答 3

0

尝试将您的体型从 更改x-www-form-urlencodedform-data,看看它是否有效:

如下图所示:
在此处输入图像描述

于 2021-01-04T21:42:31.363 回答
0

我认为您正在尝试发布多张照片,最多 10 张照片?你的photo财产postSchema应该是一个数组。你应该设置它

// ...
photo: {
    type: [String], // have multiple images
    required: true
}, 

路线/add-story会是这样的,

router.post('/add-story', upload.array('photo', 10), async (req, res) => {
    const photoPath = [];
    req.files.forEach(file => {
        photoPath.push(file.path);
    });

    req.body.post = photoPath;
    const post = new Post(req.body);
    try {
        await post.save();
        return res.json({
            status: true,
            message: "Successfully saved."
        });
    } catch (err) {
        return res.status(500).json({ success: false, message: err.message });
    }
});

照片数组来自请求的二进制数据,可以作为req.files.

于 2021-01-04T22:26:48.977 回答
0

最终成为一个拼写错误。

我有:

let post = new Post();
    Post.title = req.body.title;
    Post.description = req.body.description;
    Post.photo = req.body.photo;
    Post.body = req.body.body;
    Post.snippet = req.body.snippet;

但需要:

let post = new Post();
    post.title = req.body.title;
    post.description = req.body.description;
    post.photo = req.body.photo;
    post.body = req.body.body;
    post.snippet = req.body.snippet;
于 2021-01-05T21:59:24.320 回答