0

I am needing to have 1 page of a website submit data to MongoDB then pull that same data and display it on a different page. I am using node.js, express, Mongoose, and MongoDB.

Currently, I have it so It gets submitted properly to the database, and I can see it with the correct layout, But I cannot seem to get it posted on the page.

How exactly do I go about doing this? Can someone give a example of code of this?

I am really new to this stuff and still learning. Thanks!

1 Answer 1

1

In the route of the page you want to load, use the Mongoose .find() method. You can use {} in the find() method to return all the data, or access individual data based on the object key find({id:'value'}). Then when you render the page, just pass in an object to the render, where the key is what you access in the url page, in my example you would use (mongs) to access the values within the url page (.ejs, etc). So in your route definition file:

app.get('/', (req, res) => {
    MongModel.find({}, (err, foundMongModel) => {
        err ? console.log(err) : res.render('url/route', { mongs: foundMongModel });
    });
});

Then if you're using .ejs file, you would need to use <%= %> to access individual data, and <% %> to use a loop or something. and use the mongs value. So if you imported all the data from the database, you could loop through it using

<% mongs.forEach(mong =>{ %>
        <div>mong.key<div>
<% }) %>

You can access the keys for each database object like above using mong.key

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

Comments

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.