1

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 Answer 1

1

in your creation of the object , creat it like this

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

In your code you don't actually create the array that you have defined in your schema. So tally with your schema like above and then save. below

graph.save((err) => {
if(err) {

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

})
});

this is the way you have currently posted the question.. so the answer is valid for that, but I assume this should be sufficient enough for you to figure out what was the problem ..

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. After that, what is the right way to test this via postman? Because when I tired it returned an html insted of the json.
I still get an html with this error: TypeError: Cannot read property 'id' of undefined
try trowing the error like i have done .Changed the code again check it. and let me know whats the console say when the app crashes. That happens because the app crashes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.