【问题标题】:Posting an array of objects to MongoDB in formData (ValidationError)在 formData 中将对象数组发布到 MongoDB (ValidationError)
【发布时间】:2018-09-11 14:08:28
【问题描述】:

所以我一直在努力向我的 MongoDB 发出 POST 请求,因为其中一个属性应该是一个对象数组。我一直在关注不同的教程,但仍然无法理解它。

我有一个数组,它是一个对象数组。

tagsArray = [
    { tag_name: "Tiger", ref: "t" },
    { tag_name: "Cheetah", ref: "c" }
];

我使用 Fetch API 发布它,因为它包含一个图像文件,所以我使用 formData。这就是我发布它的方式......

let formData = new FormData();

formData.append('titleImage', this.state.titleImage);
for (var i = 0; i < tagsArray.length; i++) {
    formData.append('tags', JSON.stringify(tagsArray[i]));
}

var request = {
    body: formData,
    method: "POST"
}

fetch("http://localhost:3500/posts", request)
.then(res => res.json())
.then(json => {
    console.log("Post success:", json);
})
.catch(function(err) {
    console.log(err.message);
});

继续,我创建了一个架构,您可以在这里看到:

const mongoose = require('mongoose');

const tagSchema = mongoose.Schema({
    tag_name: String,
    ref: String
})

const postSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    titleImage: { type: String, required: true },
    tags: { type: [tagSchema], required: true},
});

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

这就是我一直试图将它保存到我的数据库的方式。

exports.create_post = (req, res, next) => {
    const post = new Post({
        _id: new mongoose.Types.ObjectId(),
        titleImage: req.file.path,
        tags: req.body.tags,
    });
    post.save().then(result => {
        res.status(201).json({
            post: {
                _id: result._id,
                tags: result.tags
            }
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
}

这是控制台中记录的错误。

消息:'转换为数组失败,值“[ \'{"tag_name":"Tiger","re​​f":"t"}\',\n \'{"tag_name":"Cheetah","re​​f":"c"}\' ]" 在路径 "tags"', 名称:'CastError', stringValue: '"[ \'{"tag_name":"Tiger","re​​f":"t"}\',\'{"tag_name":"Cheetah","re​​f":"c"}\' ]"', 种类:'数组', 值:[数组], 路径:'标签', 原因:[对象] } },_message:'后验证失败',名称:'ValidationError' }

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    与往常一样,当我发布问题时,我的竞争精神和自我意识会激发出新的能量和动力,让我更加专注并完成工作。所以这就是我解决问题的方法。

    我像这样更改了 postSchema:

    const postSchema = mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,
        titleImage: { type: String, required: true },
        tags: { type: {tagName: String, tagRef: String}, required: true}
    });
    

    这里很少有配置,我获取标签数组并将其映射并将每个字符串转换为一个对象,这样我就可以访问每个属性。

    exports.create_post = (req, res, next) => {
        const post = new Post({
            _id: new mongoose.Types.ObjectId(),
            titleImage: req.file.path,
            tags: req.body.tags.map(tag => {
                var tagObject = JSON.parse(tag);
                return {
                    tagName: tagObject.tag_name,
                    tagRef: tagObject.ref
                }
            })
        });
        post.save().then(result => {
            res.status(201).json({
                post: {
                    _id: result._id,
                    tags: result.tags.map(tag => {
                        return {
                            tagName: tag.tagName,
                            tagRef: tag.tagRef
                        }
                    }),
                }
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error: err
            });
        });
    }
    

    不确定是否是最好的解决方案,但对我来说效果很好。

    【讨论】:

      猜你喜欢
      • 2016-04-02
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-06
      相关资源
      最近更新 更多