【问题标题】:Mongoose model keys not being inserted in Postman post request猫鼬模型密钥未插入 Postman 发布请求中
【发布时间】:2018-07-18 06:38:42
【问题描述】:

我正在尝试使用下面的 post 方法来创建新文档。但是当我在 Postman 中发送一个帖子请求(例如http://localhost:3000/api/posts?title=HeaderThree)时,会创建一个新文档,但缺少键和值。

router.route('/posts')
    .get(function(req, res) {
        Post.find(function(err, posts) {
            if (err) { return res.send(err)}
            res.json(posts)
        })
    })
    .post(function(req, res) {
        const post = new Post(
            {
                title: req.body.title,
                text: req.body.text
            }
        );

        post.save(function(err, post) {
            if (err) { return res.send(err)};
            res.json({ message: 'Post added!'});
        });
    });

架构是这样的:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const PostSchema = new Schema(
    {   
        date: {type: Date, default: Date.now},
        title: {type: String},
        text: {type: String },
        comments: {type: Array}
    }
)

module.exports = mongoose.model('PostSchema', PostSchema);

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    如果您将数据作为查询字符串发送:

     http://localhost:3000/api/posts?title=HeaderThree
                                     ^^^^^^^^^^^^^^^^^
    

    那么你必须使用req.query从快递服务器获取它们:

    const post = new Post(
        {
            title: req.query.title,
            text: req.query.text
        }
    );
    

    如果要将数据作为表单体发送,需要使用body-parser中间件:

    const bodyParser = require('body-parser');
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    ...
    

    现在您可以使用req.body 对象来获取提交的数据。

    最后一件事,不要忘记在邮递员的正文选项卡下填充表单数据

    【讨论】:

    • 我将正文更改为查询,现在它可以完美运行。不过,我一定在其他地方犯了错误,因为我已经包含了 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true }));
    【解决方案2】:

    尝试添加:

      _id: mongoose.Schema.Types.ObjectId,
    

    在你的模型中:

    const PostSchema = new Schema(
        {   
            _id: mongoose.Schema.Types.ObjectId,
            date: {type: Date, default: Date.now},
            title: {type: String},
            text: {type: String },
            comments: {type: Array}
        }
    )
    

    在插入文档之前,您必须给它一个 _id :

    _id : mongoose.Types.ObjectId()

    您的文件将是:

    const post = new Post(
                {
                    _id :  mongoose.Types.ObjectId(),
                    title: req.body.title,
                    text: req.body.text
                }
            );
    

    检查这个post

    【讨论】:

    • 我试过了,它返回 { "message": "document must have an _id before save", "name": "MongooseError" }
    • 现在它又回到了以前的状态。它使用默认日期和 id 创建一个文档,但不包括 req.body 值。
    猜你喜欢
    • 2013-07-21
    • 1970-01-01
    • 2017-04-23
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2022-09-28
    相关资源
    最近更新 更多