【问题标题】:Can't add values from req.body to mongoose Schema无法将 req.body 中的值添加到 mongoose Schema
【发布时间】:2019-04-26 21:13:50
【问题描述】:

我正在尝试上传一张带有“价格”等额外字段的小图片。 img 似乎存储在 destination 文件夹中,但额外的字段未与文件一起保存。

我正在使用 multer 和 bodyParser.json 来读取 req.body 和 req.file 的字段。

这是帖子:

router.route('/pictures/add').post(upload, (req, res) => {


        console.log(req.body.price); //works
        console.log(req.file); //works

    var picture = new Picture({
        name : req.file.originalname,
        price : req.body.price,
        id : req.file.filename
    }); 


    console.log(picture); //logs only the id as in req.file.filename. 
    //name and price are missing

    picture
        .save()
        .then(picture => {
            console.log(picture);
            res.status(201).json({
                picture: 'Added successfully',
                id: picture.id, //id as in req.file.filename
                name: picture.name, //missing
                price: picture.price //missing
            });
        })

这是 multer 实例

const upload = multer({dest: 'pictures/'}).single('img');
app.use(bodyParser.json());

这是图片架构

import mongoose from 'mongoose';

const Schema = mongoose.Schema;

let Picture = new Schema({
    name: {
        Type: String
    },
    price: {
        Type: String
    }
});

export default mongoose.model('Picture', Picture);

我希望数据库能像这样保存所有字段:id、name、price 但似乎只有 id 被发送并保存到数据库中。

我欢迎任何帮助。

【问题讨论】:

  • 显示 req.body.price 和 req.file

标签: javascript node.js mongodb express


【解决方案1】:

答案很简单:定义模式类型时,关键字“type”必须是小写,而不是大写。在我为字段“name”设置默认值后,服务器抛出异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2020-10-20
    • 2019-04-12
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多