简体   繁体   English

如何提交数据然后在另一页上发布mongoDB / Node.js

[英]How to submit data then post on another page mongoDB/Node.js

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. 我需要网站的一页提交数据到MongoDB,然后提取相同的数据并将其显示在另一页上。 I am using node.js, express, Mongoose, and MongoDB. 我正在使用node.js,express,Mongoose和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! 谢谢!

In the route of the page you want to load, use the Mongoose .find() method. 在要加载的页面的路线中,使用Mongoose .find()方法。 You can use {} in the find() method to return all the data, or access individual data based on the object key find({id:'value'}) . 您可以在find()方法中使用{}返回所有数据,或基于对象键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). 然后,在渲染页面时,只需将一个对象传递到渲染器,该键就是您在url页面中访问的键,在我的示例中,您将使用( mongs )访问url页面中的值(.ejs等) )。 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. 然后,如果您使用的是.ejs文件,则需要使用<%= %>来访问单个数据,而需要使用<%= %> <% %>来使用循环或其他方式。 and use the mongs value. 并使用mongs值。 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 您可以使用mong.key像上面那样访问每个数据库对象的键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM