save() is not a function haraka plugin + mongoose

164 views Asked by At

I'm trying to create a plugin for haraka mailserver to support saving emails to mongodb. The plugin is running fine however when I send a test email it's giving me this error:

Plugin queue/mongo_email failed: TypeError: Email.save is not a function

This is the plugin code:

var mongoose         = require('mongoose');

var mongodbUri = "mongodb://localhost:27017/";

var options = {
  useMongoClient: true,
  socketTimeoutMS: 0,
  keepAlive: true,
  reconnectTries: 30
};

var db = mongoose.connect(mongodbUri, options);

var EmailSchema = mongoose.Schema({
  emailFrom: String,
  emailMsg: String,
  emailRcv: String,
  emailSubject: String
});

var Email = mongoose.model('Email', EmailSchema);

exports.hook_queue = function(next, connection){

    var transaction   = connection.transaction;
    var receivedDate  = transaction.header.headers.date;
    var subjectLine   = transaction.header.headers.subject;

    Email.save({
      emailFrom: transaction.mail_from,
      emailMsg: transaction.data_lines,
      emailRcv: receivedDate,
      emailSubject: subjectLine
    });

    next();

}
1

There are 1 answers

0
tosi On BEST ANSWER

Answer:

var mongoose         = require('mongoose');

var mongodbUri = "mongodb://localhost:27017/";

var options = {
  useMongoClient: true,
  socketTimeoutMS: 0,
  keepAlive: true,
  reconnectTries: 30
};

var db = mongoose.connect(mongodbUri, options);

var EmailSchema = mongoose.model('Email',{
  emailFrom: String,
  emailMsg: String,
  emailRcv: String,
  emailSubject: String
});


exports.hook_queue = function(next, connection){

    var transaction   = connection.transaction;
    var receivedDate  = transaction.header.headers.date;
    var subjectLine   = transaction.header.headers.subject;

    var Email = new EmailSchema({
      emailFrom: transaction.mail_from,
      emailMsg: transaction.data_lines,
      emailRcv: receivedDate,
      emailSubject: subjectLine
    });

    Email.save();

    next();

}

The transaction variable var transaction = connection.transaction; is an object containig all information regarding new emails. The mongodb schema EmailSchema can be modified to support other options such as message headers, attachments, etc.