【问题标题】:Post data to mongodb将数据发布到 mongodb
【发布时间】:2018-11-27 17:57:19
【问题描述】:

您好,我有将数据发布到 mongodb 的终点,当我提交表单时,我认为只提交了 ID,因为我使用的是插入而不是保存,

这是它的外观:

app.post('/comments', (req, res) => {
        const { errors, isVal } = validate(req.body);
        if (isVal){
            const { author, description } = req.body;
            db.collection('comments').insert({ author, description }, (error, result) => {
                if (error) {
                    res.status(500).json({ errors: { global: "Oops something is right!" }});
                } else {
                    res.json({ comments: result.ops[0] });
                } 
            })

        } else {
            res.status(400).json({ errors });
        }

    }); 

上面的方法是只保存ID,其他数据保存为null:我尝试这样更改,将insert替换为save some one,建议类似这样。

app.post('/comments', (req, res) => {
        const { errors, isVal } = validate(req.body);
        if (isVal){
            const { author, description } = req.body;
            db.collection('comments').save({ author, description }, (error, result) => {
                if (error) {
                    res.status(500).json({ errors: { global: "Oops something is right!" }});
                } else {
                    res.json({ comments: result.ops[0] });
                } 
            })

        } else {
            res.status(400).json({ errors });
        }

    });

还是一样:这是保存在数据库中的结果:

{
    "_id": {
        "$oid": "5b281457f5b629565c09ce26"
    },
    "author": null,
    "description": null
}

如何更改我的方法以便它可以使用保存而不是插入? mongodb中的save和insert有什么区别?

【问题讨论】:

    标签: javascript node.js mongodb typescript


    【解决方案1】:

    试试这个 让 newcollection = db.collection('cmets'); newcollection.insert({})

    【讨论】:

    • 还是一样!
    • 尝试在这个 const { author, description } = req.body;保存函数需要一个对象。
    • undefined undefined 来自控制台的结果。
    • console req.body after const { author, description } = req.body;
    • 状态码:200 {}
    猜你喜欢
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多