【问题标题】:Post to a mongoose schema with array of objects发布到带有对象数组的猫鼬模式
【发布时间】:2019-06-09 19:26:38
【问题描述】:

我想将一些数据发布到我的 mongo 数据库。

但是架构的结构让我对实现感到困惑。

这是架构:

var GraphSchema = new Schema({
nodes: [{id: String}],
links: [{source:String, target: String}]
});

这是我迄今为止尝试过的,但它似乎不起作用:

router.post('/graphs', (req, res) => {
const graph = new Graph();
graph.nodes = [{id: req.body.nodes.id}];
graph.links = [{source: req.body.source, target: req.body.target}];


graph.save((err) => {
if(err) return res.status(500).json({ message: 'internal error' })
res.json({ message: 'saved...' })
})
});

例如,我想实现这样的最终结果:

{
"data": [
    {
        "nodes": [
            {
                "id": "root"
            },
            {
                "id": "input"
            },
            {
                "id": "component"
            }
        ],
        "links": [
            {
                "source": "component",
                "target": "root"
            }
        ]
    }
]
}

我正在使用 Postman 测试操作 关于如何继续,我陷入了死胡同,所以我希望你能给我一些提示!

【问题讨论】:

    标签: mongodb post postman mongoose-schema


    【解决方案1】:

    在创建对象时,像这样创建它

    router.post('/graphs', (req, res) => {
    
    const graph = new Graph({
     nodes:[{id:req.body.nodes.id}],
     links:[{source: req.body.source, target: req.body.target}]
    }); // you need to include your data inside the instance of the model when you create it that was the problem.. It should work fine now
    

    在您的代码中,您实际上并没有创建您在架构中定义的数组。所以像上面那样与你的模式相吻合,然后保存。下面

    graph.save((err) => {
    if(err) {
    
    res.status(500).json({ message: 'internal error' });
    throw err;
    }else{
    res.send({ message: 'saved...' });
    }
    
    })
    });
    

    这是您当前发布问题的方式..所以答案对此有效,但我认为这应该足以让您找出问题所在..

    【讨论】:

    • 感谢您的回答。之后,通过邮递员进行测试的正确方法是什么?因为当我累的时候,它返回了一个 json 的 html。
    • 我仍然收到带有此错误的 html:TypeError: Cannot read property 'id' of undefined
    • 尝试像我一样处理错误。更改代码再次检查它。让我知道当应用程序崩溃时控制台会说什么。发生这种情况是因为应用程序崩溃
    猜你喜欢
    • 2019-10-30
    • 2023-03-13
    • 2016-11-09
    • 2019-08-21
    • 2020-07-27
    • 2016-09-02
    • 2021-11-04
    • 2019-02-20
    • 2021-02-09
    相关资源
    最近更新 更多