nihulus
nihulus

Reputation: 1495

How to push out requested data from mongodb in node.js

I'm working with Node.js, express, mongodb, and got stuck on this data passing between frontend and backend.

Note: code below is middleware code for front- and backend communication

Here I successfully get the input value from the frontend by using req.body.nr

exports.find_user_post = function(req, res) {
    member = new memberModel();
    member.desc = req.body.nr;
    console.log(req.body.nr);
    member.save(function (err) {
        res.render('user.jade', );
    });
};

Here is the problem, I need to use the input value I got to find the correct data from my database(mongodb in the backend) and push out to the frontend.

My data structure {desc : ''}, the desc is correspond to the input value so it should look something like this {desc: req.body.nr} which is probably incorrect code here?

exports.user = function(req, res){
    memberModel.find({desc: req.body.nr}, function(err, docs){
        res.render('user.jade', { members: docs });

    });
};

Would love to have some help.

Thanks, in advance!

Upvotes: 0

Views: 971

Answers (1)

Gianfranco P
Gianfranco P

Reputation: 10794

Have a look at this great tutorial from howtonode.org.

Because as you can see he uses a prototype and a function callback:


in articleprovider-mongodb.js

ArticleProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, article_collection) {
      if( error ) callback(error)
      else {
        article_collection.find().toArray(function(error, results) {
          if( error ) callback(error)
          else callback(null, results)
        });
      }
    });
};

exports.ArticleProvider = ArticleProvider;

in app.js

app.get('/', function(req, res){
    articleProvider.findAll( function(error,docs){
        res.render('index.jade', { 
            locals: {
                title: 'Blog',
                articles:docs
            }
        });
    })
});

Also make sure you have some error checking from the user input as well as from the anybody sending data to the node.js server.

PS: note that the node, express and mongo driver used in the tutorial are a bit older.

Upvotes: 1

Related Questions