首页 > 解决方案 > 将数据发布到 mongodb

问题描述

嗨,我有将数据发布到 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中保存和插入有什么区别?

标签: javascriptnode.jsmongodbtypescript

解决方案


试试这个 let newcollection = db.collection('comments'); newcollection.insert({})


推荐阅读