最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Display the data onto webpage retrieved from mongodb using node.js - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Jun 23, 2013 at 0:43 AstonAston 211 silver badge3 bronze badges 1
  • 2 Wele to StackOverflow Aston. Please include some of your code, so that members of the munity can help you. To help you without any code, could be very plex and time consuming. – Hanlet Escaño Commented Jun 23, 2013 at 1:02
Add a ment  | 

1 Answer 1

Reset to default 6

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

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!
发布评论

评论列表(0)

  1. 暂无评论