// Set our collection
var collection = db.get(‘usercollection’);
// Submit to the DB
collection.insert({
“username” : userName,
“email” : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send(“There was a problem adding the information to the database.”);
}
else {
// If it worked, set the header so the address bar doesn’t still say /adduser
res.location(“userlist”);
// And forward to success page
res.redirect(“userlist”);
}
});
}
}
显然在真正的项目里你还需要做很多验证,比如用户名和email不允许重复,email地址必须符合一定的格式规则。不过现在我们先不管这些。你可以看到,当插入数据库完成时,我们让用户跳转回userlist页面,他们应该在那里看到新插入的数据。
这是最好的方式吗?
第3步 – 连接数据库,写入数据
确保你的mongod在运行!然后重启你的node服务器。用浏览器打开http://localhost:3000/newuser。现在我们填入一些内容,点击提交按钮。如果顺利,我们应该回到了userlist页面,并且看到了刚刚添加的新数据。
现在我们正式的完成了使用Node.js,Exress,Ejs读取和写入Mongodb数据库,我们已经是牛X的程序员了。
恭喜你,真的。如果你认真的看完了这篇教程,并且很认真的学习而不只是复制代码,你应该对routes, views,读数据,写入数据有了完整的概念。这是你用来开发任何其它完整的Web网站所需要的一切知识点!不管你怎么想,我觉得这真挺酷的。
第5部分 – 下一步









