使用node.js将数据显示到从mongodb检索的网页上 [英] Display the data onto webpage retrieved from mongodb using node.js

查看:113
本文介绍了使用node.js将数据显示到从mongodb检索的网页上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题.可能有些琐碎.我正在使用node.js编写具有单选按钮,下拉框的表单.我已经能够保存数据并成功检索它,但无法将其写到网页上.将数据写到页面上的正确方法是什么

Heres my problem. Might be a bit trivial. I am using node.js to write a form which has radio buttons, drop down boxes. I have been able to save data and also retrieve it successfully but I am not able to write it onto web page. What is the correct way to write the data onto a page

推荐答案

您可以使用express和mongoose轻松完成此操作.首先,您将使用mongoose连接到mongoDB,然后从mongoose中设置一些用于与mongoDB进行交互的变量(即mongoose.scheme& mongoose.model),最后,您只需将express的mongoDB数据发送到网页即可res.render功能:

You can do this pretty easily with express and mongoose. First you would connect to mongoDB using mongoose, and then set up some of the variables used to interact with mongoDB from mongoose (i.e. mongoose.scheme & mongoose.model), and finally you simply send your mongoDB data to a web page through express's res.render function:

mongoose.connect('mongodb://localhost/test', function(err){
    if(!err){
        console.log('connected to mongoDB');
    } else{
        throw err;
    }
});

var Schema = mongoose.Schema,
    ObjectID = Schema.ObjectID;

var Person = new Schema({
    name : String
});

var Person = mongoose.model('Person', Person);   

app.get('/', function(req, res){
    Person.find({}, function(err, docs){
        res.render('index', { docs: docs});
    });
});

发送数据后,您只需在网页中引用"docs"变量即可. Express自动使用Jade框架.在Jade中,您可以执行以下操作:列出数据库中所有人员的姓名:

After sending the data, you can simply reference the 'docs' variable in your web page. Express automatically uses the Jade framework. In Jade you could do something like list all the names of the people in your database:

- if(docs.length)
    each person in docs
      p #{person.name}
- else
    p No one is in your database!

这篇关于使用node.js将数据显示到从mongodb检索的网页上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆