Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Reading user input from Node.js and saving it in MongoDB

Reading user input from Node.js and saving it in MongoDB


I currently have node.js, express, and mongodb in my heroku environment.

What I want to know is how do I get a user's input (example: they're signing up for an account and they're inputting their username and password) and save it in mongodb then get that information later (example: they're logging in).

Do I make a connection from a .js script to mongodb or how does it work exactly?

Problem courtesy of: Ator


Are you trying to utilize Node.js as the backend server for handling data? Will node.js be rendering the HTML pages?

Assuming that you simply want to use Node.js for inserting or finding data, take a look at Express.

Alternatively, you can do use the url library for processing incoming requests and then pass them off to Mongo using the methods provided by a library such as node-mongodb-native.

The node-mongodb-native driver gives you all the core MongoDB functionality, but depending on the complexity of your application, it might make more sense to use a framework or a mongodb library that also does data modeling.

Take a look at this Node modules list to see what all the options are.

As for the architecture, one example is to POST user credentials to Node.js which parses them and connects to MongoDB to pull the user's account info. MongoDB returns to Node.js the data it finds, and your Node server outputs the user account info in a JSON format. I'm not sure if that's what you were asking, but it's one simple approach that would be easy to build once you're familiar with the flow of callbacks and all that other tasty spaghetti ;)

Here's a little CoffeeScript snippet from a Node.js application I use to connect to Mongo and start the Node.js server:

db = new mongo.Db('tracker', new mongo.Server('', 27017, {auto_reconnect: true}))

# Open the connections: (db_error, database) ->

  console.error "Unable to open connection to database 'tracker': #{db_error}" if db_error

  # Launch server on port 8080:
  http.createServer(onRequest).listen 8080, ''

  # Close the connection if the server is stopped:
Solution courtesy of: Marco


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Reading user input from Node.js and saving it in MongoDB


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription