Post to a mongoose schema with array of objects

时间:2019-01-15 18:16:37

标签: mongodb post postman mongoose-schema

I want to post some data to my mongo database.

However the structure of the schema confuses me about the implementation.

This is the schema:

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

This is what I've tried so far but it doesn't seem to working:

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...' })
})
});

For example I want to achieve something like this as a final result:

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

I a testing the operation with Postman I am in a kind of dead end regarding how to proceed so I hope you can hint me something!

1 个答案:

答案 0 :(得分:0)

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

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...' });
}

})
});

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