I have watched and read loads of tutorials now on node.js and mongodb. I know how to create databases, Insert data, show that data on a ejs file, etc etc. However, I have no idea how to insert data from that ejs file.
For example:
I have an app.js
and a mongodb.js
the app runs my server and the mongodb.js creates a database and inserts some data - not with mongoose but rather with mongodb. I also have a few ejs files that get the data from mongodb.js and displays it. Heres my mongodb.js:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
exports.drinks = [
{ name: 'Manu', rate: 3 },
{ name: 'Martin', rate: 5 },
{ name: 'Bob', rate: 10 }
];
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('users');
// Insert some users
collection.insert(exports.drinks, function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
console.log(collection.users.find());
//Close connection
db.close();
});
}
});
Then in my app.js I have this:
//index page
app.get('/', function(req, res) {
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
And on my ejs:
<ul>
<% drinks.forEach(function(drink) { %>
<li><%= drink.name %> : <%= drink.rate %></li>
<% });; %>
</ul>
But now I want to be able to update/insert data into my database from my ejs (or even from my app.js).
For example if I have a form and I want the user to type their name inside I want that to be saved in my db. How do I do this?