我正在尝试关注此Express.js and MongoDB tutorial,不同之处在于我的索引页面有一个用于保存电子邮件地址的表单。
这是到目前为止的主要代码:
emailprovider.js
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmailProvider = function(host, port) {
this.db= new Db('email-test', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
EmailProvider.prototype.getCollection= function(callback) {
this.db.collection('emails', function(error, email_collection) {
if( error ) callback(error);
else callback(null, email_collection);
});
};
//save new email
EmailProvider.prototype.save = function(emails, callback) {
this.getCollection(function(error, email_collection) {
if( error ) callback(error)
else {
if( typeof(emails.address)=="undefined")
emails = [emails];
for( var i =0;i< emails.address;i++ ) {
email = emails[i];
email.created_at = new Date();
}
email_collection.insert(emails, function() {
callback(null, emails);
});
}
});
};
exports.EmailProvider = EmailProvider;
app.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, EmailProvider = require('./emailprovider').EmailProvider;
var app = express();
app.get('/', routes.index);
app.get('/users', user.list);
//Routes
//get new email form
app.get('/email/new', function(req, res) {
res.render('email_new', {
title: 'Email Address'
});
});
//save new email
app.post('/email/new', function(req, res){
emailProvider.save({
address: req.param('name')
}, function( error, docs) {
res.redirect('/')
});
});
index.js
.form-area
form(method='post')
input(type='text', name='address', placeholder='Your email address')
input(type='submit', value='Send')
我真的不知道emailprovider中发生了什么。我有点关闭路线但是现在当我尝试保存新的电子邮件时,我收到Cannot POST /
404错误消息。这样做的正确方法是什么?
感谢。
编辑:删除了输入属性的玉语法中的额外逗号。
答案 0 :(得分:1)
您的EmailProvider变量是对函数的引用,而不是对象实例。这可能会导致两个问题:
this
运算符可能无法按照您的意愿引用EmailProvider。EmailProvider.save()
的每次调用都会再次运行db.collection
,这可能会导致性能问题,内存泄漏以及其他问题。 您应该从EmailProvider创建一个对象实例,如下所示:
var app = express();
var emailProvider = new EmailProvider(<some host>, <some port>);
...
如果 this
运算符导致问题(例如它无法识别EmailProvider方法),请在{{1}之后调用call
函数功能如下:
save
希望它会有所帮助。