Parsing array of data and sending with nodemailer? - javascript

I've got an array of data that I want to send in a table using NodeMailer that looks something like:
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: 2016-11-18T19:08:41.662Z,
updatedAt: 2016-11-18T19:08:41.662Z,
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: 2016-11-16T17:56:21.696Z,
updatedAt: 2016-11-16T17:56:21.696Z,
id: 'B01IM0K0R2'
}]
What I am trying to do i to create a loop inside my HTML and then loop through the data. I did try the below, but it seems there are limitations on what I can do.
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>{{result.forEach((item) => {<tr><td>{{asin}}</a></td><td>{{url}</td><td>{{favourite}}</td><td>{{createdAt}}</td></tr>})}}</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
Could anyone point out where I am going wrong please and what I need to do to correct my problems.

It seems you have tried to use results.forEach((item) but you placed this inside the quotes 'result.forEach((item)' which is a string and won't execute at all.
You may have used this kind of syntax in your page when you used the view engines like jade, swig etc which will do the parsing for you. But here, you should call them manually to parse this kind of syntax.
Otherwise, you can do the parsing with the array function as below where I have used array.reduce which is handy and will do the parsing nicely.
You can try the same to generate the content and append it to the html as below.
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' +
content + '</tbody></table></div>' // html body
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: '2016-11-18T19:08:41.662Z',
updatedAt: '2016-11-18T19:08:41.662Z',
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: '2016-11-16T17:56:21.696Z',
updatedAt: '2016-11-16T17:56:21.696Z',
id: 'B01IM0K0R2'
}];
var content = results.reduce(function(a, b) {
return a + '<tr><td>' + b.asin + '</a></td><td>' + b.url + '</td><td>' + b.favourite + '</td><td>' + b.reatedAt + '</td></tr>';
}, '');
console.log(content);
/*
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' + content + '</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
*/

Related

Database Query logic

I'm making 2 queries to the database.
Right now, if even one of them is undefined, I get the generic 'not found' message that is set up. This is because there's an 'else' set up at every DB query where it responds with 'not found' if a value is undefined
What I want to achieve:
If one of them is null, I want to add the value 'nil'.
Example:
field1: nil,
field2: 'value'
If both are null, then I want it to respond with the previously mentioned 'not found' message.
What's a good approach for this?
I think your goal may be achieved using 1 call to the database by using https://www.mongodb.com/docs/manual/reference/operator/aggregation/switch/ but please provide example document structure and what the expected behavior should be in a bit more detailed way.
[
{
_id: new ObjectId("634989627d163a41b75e1e13"),
name: 'Ashish Jain',
address: 'Delhi'
},
{
_id: new ObjectId("634989cc7d163a41b75e1e14"),
name: '',
address: 'India'
},
{
_id: new ObjectId("634989cc7d163a41b75e1e15"),
name: '',
address: ''
},
{
_id: new ObjectId("634989cc7d163a41b75e1e16"),
name: 'Ash',
address: ''
}
]
This is my existing data in the local database.
Following is my Node.js code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("test");
var all_docs = dbo.collection("ccn1").find({}).toArray(function(err, result) {
if (err) throw err;
for (i in result){
if(result[i]['name'] && result[i]['address']) {
console.log("name: " + result[i]['name'])
console.log("address: " + result[i]['address'])
}
else if (result[i]['name'] && !result[i]['address']){
console.log("name: " + result[i]['name'])
console.log("address: nil")
}
else if (!result[i]['name'] && result[i]['address']){
console.log("name: nil")
console.log("address: " + result[i]['address'])
}
else {
console.log("Not Found")
}
console.log()
}
db.close();
});
});
What you are seeing below the output:
(base) ashish#ashishlaptop:~/Desktop/software/node$ node "Hello World Script For MongoDB Local.js"
name: Ashish Jain
address: Delhi
name: nil
address: India
Not Found
name: Ash
address: nil

Formatting an email in JavaScript and SendGrid

I'm trying to pass a formatted string into my function, but when the email is sent the text does not appear line by line, which is what I want.
var bodySummary = nominatorName + "\n" + nominatorRegion
// Run email Cloud code
Parse.Cloud.run("sendEmail", {
toEmail: "test#gmail.com",
subject: "Email Test",
body: bodySummary
}).then(function(result) {
// make sure to set the email sent flag on the object
console.log("result :" + JSON.stringify(result));
}, function(error) {
// error
});
I'm using SendGrid and Parse Cloud Code to generate emails in my web app:
Parse.Cloud.define("sendEmail", function(request, response) {
// Import SendGrid module and call with your SendGrid API Key
var sg = require('sendgrid')('API_KEY');
// Create the SendGrid Request
var reqSG = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: {
personalizations: [
{
to: [
{
// This field is the "to" in the email
email: request.params.toEmail,
},
],
// This field is the "subject" in the email
subject: request.params.subject,
},
],
// This field contains the "from" information
from: {
email: 'no-reply#test.com',
name: 'Test',
},
// This contains info about the "reply-to"
// Note that the "reply-to" may be different than the "from"
reply_to: {
email: 'no-reply#test.com',
name: 'Test',
},
content: [
{
// You may want to leave this in text/plain,
// Although some email providers may accept text/html
type: 'text/plain',
// This field is the body of the email
value: request.params.body,
},
],
},
});
// Make a SendGrid API Call
sg.API(reqSG, function(SGerror, SGresponse) {
// Testing if some error occurred
if (SGerror) {
// Ops, something went wrong
console.error('Error response received');
console.error('StatusCode=' + SGresponse.statusCode);
console.error(JSON.stringify(SGresponse.body));
response.error('Error = ' + JSON.stringify(SGresponse.body));
}
else {
// Everything went fine
console.log('Email sent!');
response.success('Email sent!');
}
});
});
The end result email should look like this:
nominatorName
nominationRegion
Currently, it looks like this:
nominatorName nominatorRegion
There could be two ways to accomplish.
Using HTML Body
var bodySummary = nominatorName + "<br>" + nominatorRegion
Using newline escape characters
var bodySummary = nominatorName + "\r\n" + nominatorRegion
You need to replace the line break character \n with the HTML line break <br>.
For example:
var bodySummary = nominatorName + '<br>' + nominatorRegion;

Mongodb findOneAndUpdate function is inserting new document

I just need to update serviceActiveFlag status whenever i make an update api call.After an update api call,i can see a new document with empty vehicle array is created as shown below.
_id:59c76073c11d3929148f500f
vehicle:Array
_v:0
id field will override upon every put api call.
Can some one help me to resolve this issue?
schema
var localTransportSchema = new Schema({
name: { type: String, required: false, trim: true },
contact: {
addressLine1: { type: String, required: false },
serviceActiveFlag: { type: String, required: false, enum: ['Y', 'N'] },
},
vehicle: [{
vehicleType:{ type: String, required: false, enum: ['sedan', 'hatchback', 'suv', 'mpv', 'luxury'] },
}]
});
module.exports.accomodationModel = mongoose.model(collection, localTransportSchema);
controller
var updates = {
$set: {
"contact.addressLine1": req.body['addressLine1'],
"contact.serviceActiveFlag": req.body['serviceActiveFlag']
}
};
transportModel.findOneAndUpdate({ "name": req.body['providerName']},
updates, { returnOriginal: false, upsert: false }, function (err, doc) {
if (err) {
logger.error("Error while updating record : - " + err.message);
return res.status(409).json({
"Message": "Error while updating transport details for provider " + req.body['providerName'] + " in transport details table"
});
} else if (doc === null) {
logger.error("Error while updating record in transport details : - unable to update database");
return res.status(409).json({
"Message": "Error while updating transport details for provider " + req.body['providerName'] + " due to " + err.message
});
}
});
dbModel.findOneAndUpdate() of mongoose insert a new document only when your filter query(where claus) failed to find the existing document i.e there is no matching document exist in your collection.
So mongoose will insert the new document to the collection. This works similar to upsert:true of update()
Ref :Official docs about findOneAndUpdate

Merge an Item Fulfillment with an advanced template and email it Netsuite 2.0

So without the merge function below, this code sends an email on save, but I cannot for the life of me get email merge to work in Netsuite 2.0, so how do I merge an advanced pdf template with an item fulfillment and email it?
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(['N/email','N/render', 'N/record', 'N/file'],
function(email, record, file,render) {
function afterSubmit(context) {
function templatemerge() {
var myMergeResult = render.mergeEmail({
templateId: 121,
entity: {
type: 'employee',
id: 18040
},
recipient: {
type: 'employee',
id: 18040
},
supportCaseId: 'NULL',
transactionId: 1176527,
customRecord: 'NULL'
});
}
templatemerge();
function sendEmailWithAttachement() {
var newId = context.newRecord;
var emailbody = 'attachment';
var senderId = 18040;
var recipientEmail = 'email#email.com';
email.send({
author: senderId,
recipients: recipientEmail,
subject: 'Item Fulfillments',
body: emailbody
});
}
sendEmailWithAttachement();
}
return {
afterSubmit: afterSubmit
};
});
Try rearranging the first function signature to function(email, render, record, file)
They are probably in the wrong order.

Add elements in the DOM with JS

I'm trying to print in the HTML the data from another part of the site, the data appears on the console, however not in the HTML.
I believe it is an error in the code, could someone point me or direct me?
$.ajax({
type: "GET",
url: 'https://example.com',
crossDomain: true,
success: function (json) {
var reservas = json;
reservas.forEach(function (reserva) {
$(".reservas").append($("<td/>", {
html: reserva
}));
console.log(reserva);
});
},
error: function (e) {
console.log(e);
}
});
If i change the variable reservas for:
var reservas = ["test", "test2", "test3"]
And the elements are being added..
when I give console.log (reserve), the console return:
Object {
_id: "10152686662737642",
nome: "First Person",
email: "email1#gmail.com",
__v: 0
}(index):68
Object {
_id: "10152433045473800",
nome: "Second Person",
email: "email2#gmail.com",
__v: 0
} (index):68
maybe the problem is that is not an array?
Based on your clarifications. I believe what you want to do is:
$(".reservas").append($("<td/>", {
html: JSON.stringify(reserva)
}));
either that or $(".reservas") isn't finding any elements in the DOM. Also you may want to do something like:
$(".reservas").append($("<td/>", {
html: reserva.nome + " " + reserva.email
}));
instead depending on what you actually want to display

Categories