Node.js, Express, Mongoose, MongoHQ (save data)

I'm new in node.js.

I want to ask, how do we save data using mongoose?

In this case I've 3 folders to run the process

models (in this folder we have store.js)

var mongoose = require('mongoose');

mongoose.connect('mongodb://xxx:xxx@dharma.mongohq.com:10019/xxx');
var t_store = new mongoose.Schema({
   store_email : String
});

module.exports = mongoose.model('store', t_store);

routes (in this folder we have signup.js)

var store = require('../models/store');

exports.form = function(req, res) {
  res.render('signup', {
    title: 'Sign Up'
  });
};

exports.submit = function (table_name) {
  return function(req, res, next) {
    var email = req.body.signup.email;
    console.log("name " + email);

    store.create({
        store_email: email
    });
  };
};

views (in this folder we have signup.ejs)

<form method='post' enctype='multipart/form-data'>
  <input type="text" id="email" name="signup[email]" placeholder="Your email address">
  <input type='submit', value='Sign Up'/>
</form>

That was what I've done so far. Thanks!

Suggest that you install express(in addition to node.js and mongoose) and follow a guide/tutorial with that. Express will allow you to use a REST-like approach.

npm install -g express

From your app.js (application setup file) you define your routes and define which methods/REST calls each route belongs to.

I can show you an example for deleting:

In my app.js:

app.post('/deleteActivity', activityList.deleteActivity.bind(activityList))

Tells the application that posts to /deleteActivity will be handled in activityList with the method deleteActivity.

In my activityList.js:

  deleteActivity: function(req,res) {
    var item = req.body.item;
    var deleted = item.activity;
    activity.remove({_id: deleted}, function(err){
    if(!err){
      console.log('Deletes ' + item.activity);
    }
    else {
      console.log('Could not delete' + item.activity);
    }
    });
    res.redirect('/');
   }

req.body.item here contains all the data needed to delete the activity. This is sent from my index.jade file like this:

form(action="/deleteActivity", method="post")
  select(name = "item[activity]")
    each activity in activities
      option(value=activity._id) #{activity.activityType}
  input(type="submit", value="Delete activity")

As you can see, the data gets binded to the request with the values provided by the user. In this case activity._id is passed to deleteActivity.

In your case, just make a new object of your desired Schema(mongoose) and use the save method on it.

Hope this helps