【发布时间】:2015-09-14 09:51:17
【问题描述】:
我现在已经观看并阅读了大量关于 node.js 和 mongodb 的教程。我知道如何创建数据库、插入数据、在 ejs 文件中显示数据等。但是,我不知道如何从该 ejs 文件中插入数据。
例如:
我有一个app.js 和一个mongodb.js 应用程序运行我的服务器,mongodb.js 创建一个数据库并插入一些数据 - 不是使用 mongoose,而是使用 mongodb。我还有一些从 mongodb.js 获取数据并显示的 ejs 文件。这是我的 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();
});
}
});
然后在我的 app.js 中有这个:
//index page
app.get('/', function(req, res) {
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
在我的 ejs 上:
<ul>
<% drinks.forEach(function(drink) { %>
<li><%= drink.name %> : <%= drink.rate %></li>
<% });; %>
</ul>
但是现在我希望能够从我的 ejs(甚至从我的 app.js)更新/插入数据到我的数据库中。
例如,如果我有一个表单并且我希望用户在其中输入他们的姓名,我希望将其保存在我的数据库中。我该怎么做?
【问题讨论】:
-
您的 ejs 不会将数据直接保存到数据库,但应该将数据发送到您的 node.js 服务器,该服务器接收该数据并使用 mongodb 驱动程序 api 将其保存到数据库。附带说明:您应该考虑使用 mongoose,这是对 node.js 的 mongodb 的一个很好的抽象
标签: javascript node.js mongodb ejs