getting data from mongodb collection - mongodb

Trying to get some messages from a db collection, I've tried that code (server side):
MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
if(err) throw err;
var history="";
var collection = db.collection('gt-chat');
console.log("******************************Printing docs from Cursor Each")
collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
console.log(doc)
if(doc != null) {
console.log("Doc from Each ");
history=history+console.dir(doc)+"\r\n";
console.dir(doc);
}
});
console.log("/////////////HISTORY//////////////////");
console.log(history); ; // data is shown there under the shell console, all is fine !
socket.emit('updatechat', 'SERVER', history); // should send the messages using socket
});
and then on the client side, I've tried :
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
date = new Date;
h = date.getHours();
if (h<10) {
h = "0"+h;
}
m = date.getMinutes();
if (m<10) {
m = "0"+m;
}
s = date.getSeconds();
if (s<10) {
s = "0"+s;
}
var time = h+":"+m+":"+s;
$('#conversation').append('<b><strong>' + time + '</strong> '+username + ':</b> ' + data + '<br>');
});
which doesn't show anything as expected :(
I am quite sure about the updatechat function because I can get message with it, as I've tried:
socket.emit('updatechat', 'SERVER',"this is history"); // < message is well sent, so no problem there!
but I don't get the all history.
So the goal is to get some messages from a mongodb collection and to display them under the browser using socket emit
Under the shell, to debug, it's showing:
Doc from Each { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' } { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' }
So, data and messages exist, but I can't read them from the browser. The shell says: 'history is not defined' ! What is wrong with concatenation? And my variable declaration? I don't understand, thanks for your help!

Related

Send message and leave server on ready event if not whitelisted (Discord.JS + MongoDB)

I'm coding a whitelist system for my discord bot that, on ready event (and after a 3 seconds delay), checks if every server it is in has it's ID added to the whitelist database on MongoDB. If not, the bot sends an embed and leaves the server. I managed to get it working on the guildCreate event, but on ready event it performs the message and leave actions on every single server without filtering conditions, even though those are added to the list. I cannot figure out why. Also, I'm still new to JavaScript, so it could be just a minor mistake.
//VARIABLES
const { Client, MessageEmbed } = require("discord.js")
const config = require('../../Files/Configuration/config.json');
const DB = require("../../Schemas/WhitelistDB");
//READY EVENT
module.exports = {
name: "ready",
once: false,
async execute(client) {
//[ ... ] <--- OTHER UNNECESSARY CODE IN BETWEEN
setTimeout(function() { // <--- 3 SECONDS DELAY
client.guilds.cache.forEach(async (guild) => { // <--- CHECK EVERY SERVER
await DB.find({}).then(whitelistServers => { // <--- CHECK MONGODB ID LIST
if(!whitelistServers.includes(guild.id)) {
const channel = guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').random(1)[0]; // <--- SEND MESSAGE TO RANDOM TEXT CHANNEL (It is sending to every server, when it should be sending only to the not whitelisted ones)
if(channel) {
const WhitelistEmbed = new MessageEmbed()
WhitelistEmbed.setColor(config.colors.RED)
WhitelistEmbed.setDescription(`${config.symbols.ERROR} ${config.messages.SERVER_NOT_WHITELISTED}`)
channel.send({embeds: [WhitelistEmbed]});
}
client.guilds.cache.get(guild.id).leave(); // <--- LEAVE SERVER (It is leaving every server, when it should be leaving only the not whitelisted ones)
} else { return }
});
});
}, 1000 * 3);
}
}
I found the solution myself!
Instead of finding the array of whitelisted ID's for each guild, find one at a time and instead of checking the content of the array, check if the array exists. This is the updated code:
//WHITELIST
setTimeout(function() {
client.guilds.cache.forEach(async (guild) => {
await DB.findOne({ GuildID: guild.id }).then(whitelistServers => {
if(!whitelistServers) {
const channel = guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').random(1)[0];
if(channel) {
const WhitelistEmbed = new MessageEmbed()
WhitelistEmbed.setColor(config.colors.RED)
WhitelistEmbed.setDescription(`${config.symbols.ERROR} ${config.messages.SERVER_NOT_WHITELISTED}`)
channel.send({embeds: [WhitelistEmbed]});
}
client.guilds.cache.get(guild.id).leave();
} else { return }
});
});
}, 1000 * 3);

TypeError seneca indexof if not a function during respond

I have written a simple action which connects to mongo db using seneca-mongo store module, execute a list query and get the results. I can see that the query was successful and the correct results were fetched. When I try to send these results back to the client, the respond call errors out with following message and stack trace.
ERROR act root$ OUT cmd:getparams,role:diff 11 {cmd:getparams,role:diff,payload:{id:scalaScan}} ENTRY (dqk22) - seneca: Action cmd:getparams,role:diff callback threw: k.indexOf is not a function. act_callback {message:k.indexOf is not a function,pattern:cmd:getparams,role:diff,instance:Seneca/0.7.2/d0twcki9cmxg/1485517 TypeError: k.indexOf is not a function
at /scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:851:13
at Function.forEach (/scratch/DiffAnalyzer/node_modules/lodash/dist/lodash.js:3298:15)
at Object.defaultmodify [as modify] (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:850:7)
at respond (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:654:22)
at Seneca.<anonymous> (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:401:7)
at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
at Seneca.<anonymous> (/scratch/DiffAnalyzer/analyze.js:613:5)
at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
at /scratch/DiffAnalyzer/node_modules/seneca-mongo-store/mongo-store.js:329:21
at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:271:33
at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:35
at Cursor.close (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:1009:5)
at Cursor.nextObject (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:17)
at Cursor.each (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:264:12)
The action that I have written is
seneca.add("role:diff,cmd:getparams", function(msg, respond) {
seneca.ready(function() {
var collection = seneca.make$("paramStore");
var f = msg.payload;
seneca.log.info("Filter", f);
collection.list$(f, function(err, ob) {
if (err) {
seneca.log.error(err);
respond(err);
} else {
seneca.log.info("Result", ob);
respond(null, ob);
}
});
});
});
The same piece of code was working and now I am getting this error. Not sure what changed. Any help/suggestions are greatly appreciated.
The issue I was facing was because of this bit of code in the module's js file
if( _.isObject( result.out ) ) {
_.each(result.out,function(v,k){
if(~k.indexOf('$') && 'http$' !== k) {
delete result.out[k]
}
})
The _.each function is meant to parse a JSON object, where in my case the out was actually a JSON array. Wrapping the array into an object resolved it.

Fromname in mail using sendgrid mail api

I'm trying to send emails using sendgrid mail API.
Everything works fine. However, I want my emails to have a specific name.
Not the prefix of the sender's address, which is coming up by default.
I changed the From value to "MY_email_name <sender#example.com>". But it didn't work.
I have set the From_Name field to "MY_email_name". That too didn't work.
However, it's working when I not read the html content from an external file and instead give some inline. In that case it is sending me the email_name.
Any idea about how I can do this with reading the content.
Thanks.
var sendgrid = require('sendgrid')('MY_APP_SECRET');
var fs = require('fs');
var content;
// First I want to read the file
fs.readFile(__dirname+'/email.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
// Invoke the next step here however you like
//console.log(content); // Put all of the code here (not the best solution)
processFile(); // Or put the next step in a function and invoke it
});
function processFile() {
console.log(content);
}
module.exports = function sendMail(mailObject){
return new Promise(function (resolve, reject){
// create a new email instance
var email = new sendgrid.Email();
email.addTo('some1#example.com');
email.setFrom('sender#example.com');
email.setSubject('My-Email-body');
email.setFromName("Email-Name");
email.setHtml(content);
email.addHeader('X-Sent-Using', 'SendGrid-API');
email.addHeader('X-Transport', 'web');
email.setASMGroupID(835);
//send mail
sendgrid.send(email, function(err, json) {
//if something went wrong
if (err) { reject({
error:err,
res : json,
}); }
//else
resolve({
statusText: 'OK',
res : json
});
});
})
}

Read file from GridFS based on _ID using mongoskin & nodejs

I am using mongoskin in my nodejs based application. I have used GridFS to uplaod the file. I am able to upload and read it back using the "filename" however I want to read it back using _id. How can i do? Following are code details.
Working code to read the file based on filename:
exports.previewFile = function (req, res) {
var contentId = req.params.contentid;
var gs = DBModule.db.gridStore('69316_103528209714703_155822_n.jpg', 'r');
gs.read(function (err, data) {
if (!err) {
res.setHeader('Content-Type', gs.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id '+contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};
How this code can be modified to make it work based on id?
After few hit & trial following code works. This is surprise bcz input parameter seems searching on all the fields.
//view file from database
exports.previewContent = function (req, res) {
var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
console.log('Calling previewFile inside FileUploadService for content id ' + contentId);
var gs = DBModule.db.gridStore(contentId, 'r');
gs.read(function (err, data) {
if (!err) {
//res.setHeader('Content-Type', metadata.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id ' + contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};

Meteor code must always run within a fiber when deploy in meteor server

I kept having this error when i deploy my app onto meteor cloud server.
Meteor code must always run within a Fiber
at _.extend.get (app/packages/meteor/dynamics_nodejs.js:14:13)
at _.extend.apply (app/packages/livedata/livedata_server.js:1268:57)
at _.extend.call (app/packages/livedata/livedata_server.js:1229:17)
at Meteor.startup.Meteor.methods.streamTwit (app/server/server.js:50:24)
however, I have already wrapped within Fibers
streamTwit: function (twit){
var userid = '1527228696';
twit.stream(
'statuses/filter',
{ follow: userid},
function(stream) {
stream.on('data', function(tweet) {
Fiber(function(){
if(tweet.user.id_str === userid)
{
Meteor.call('addQn', tweet);
}
}).run();
console.log(tweet);
console.log('---------------------------------------------------------');
console.log(tweet.user.screen_name);
console.log(tweet.user.name);
console.log(tweet.text);
});
}
);
}
I don't know what's the reason but someone suggested that i should wrap it with Meteor.bindEnvironment instead. Hence, I did this:
streamTwit: function (twit){
this.unblock(); // this doesn't seem to work
console.log('... ... trackTweets');
var _this = this;
var userid = '1527228696';
twit.stream(
'statuses/filter',
{ follow: userid},
function(stream) {
stream.on('data', function(tweet) {
Meteor.bindEnvironment(function () {
if(tweet.user.id_str === userid)
{
Meteor.call('addQn', tweet);
}
}, function(e) {
Meteor._debug("Exception from connection close callback:", e);
});
console.log(tweet);
console.log('---------------------------------------------------------');
console.log(tweet.user.screen_name);
console.log(tweet.user.name);
console.log(tweet.text);
});
}
);
}
//add question method
addQn:function(tweet){
questionDB.insert({'tweet': tweet, 'date': new Date()});
}
but now it doesn't even work. I realise that this only happened when I tried to insert some data into mongodb.
May I know what is the problem with my code? Thanks!
All these codes were written in app/server/server.js
You shouldn't need to use Meteor.call on the server side. That is for client-side code only. Just call addQn directly or better yet, inline it since it's just one line of code.