Error Connecting Google Sheets to Node JS - node.js

I'm trying to have a spreadsheet interact with node js and I'm having connectivity issues. I don't quite know where I'm going wrong and I can't seem to find a remedy to my situation. My code is below and it is a mix of Twilio and what I've found here:
const GoogleSpreadsheet = require('google-spreadsheet');
const creds = require('./credentials.json');
// spreadsheet key is the long id in the sheets URL
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('XXX');
await doc.useServiceAccountAuth({
client_email: creds.client_email,
private_key: creds.private_key,
});
await doc.loadInfo(); // loads document properties and worksheets
console.log(doc.title);
const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id]
console.log(sheet.title);
console.log(sheet.rowCount);
}
accessSpreadsheet();
I'm new to JavaScript so I don't really know how to properly handle these errors. My error messages are below:
(node:15432) UnhandledPromiseRejectionWarning: TypeError: doc.loadInfo is not a function
at accessSpreadsheet (/home/spreadsheet.js:13:13)
(node:15432) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15432) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
/home/index.js:77
cb()
^
TypeError: cb is not a function
at /home/google-spreadsheet/index.js:77:7
at /home/node_modules/google-auth-library/lib/auth/jwtclient.js:119:5
at /home/node_modules/google-auth-library/lib/auth/jwtclient.js:138:16
at Request._callback (/home/node_modules/gtoken/lib/index.js:228:14)
at Request.self.callback (/home/node_modules/request/request.js:185:22)
at Request.emit (events.js:203:13)
at Request.<anonymous> (/home/node_modules/request/request.js:1154:10)
at Request.emit (events.js:203:13)
at IncomingMessage.<anonymous> (/home/node_modules/request/request.js:1076:12)
at Object.onceWrapper (events.js:291:20)

Related

(node:23468) UnhandledPromiseRejectionWarning: MongoServerError: FieldPath field names may not start with '$'. Consider using $getField or $setField

I am facing an issue using node.js and mongoose, when I am trying to run the following query I get this error. I tried almost every possible solution but nothing helped out.
my mongo DB version is 5.0.6, node.js is v14.17.1 and the mongoose version is ^6.0.10
const getConversationsToJoin = async(userId) => {
const conversations = await Conversation.find({ status: 'active' }, {
$or: [{
member_a_id: userId
},
{
member_b_id: userId
}
]
});
return conversations
}
(node:23468) UnhandledPromiseRejectionWarning: MongoServerError: FieldPath field names may not start with '$'. Consider using $getField or
$setField.
at MessageStream.messageHandler (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\connection.js:467:30)
at MessageStream.emit (events.js:375:28)
at processIncomingData (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at Socket.ondata (internal/streams/readable.js:726:22)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
(Use node --trace-warnings ... to show where the warning was created)
(node:23468) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:23468) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Please help
Your issue is nothing related to the version of technologies used, it's an incorrect use of find query. Find query will only take one argument, that is supposed to contain all your filters.
Moreover the syntax for $or is incorrect too. It should not be wrapped inside curly braces.
Here is what you should be doing:
const getConversationsToJoin = async (userId) => {
const conversations = await Conversation.find({
status: "active",
$or: [
{
member_a_id: userId,
},
{
member_b_id: userId,
},
],
});
return conversations;
};

I have a problem with my Discord bot (Minecraft server status bot)

This is the index.js script of the bot:
const { Client, RichEmbed } = require('discord.js')
const bot = new Client()
const util = require('minecraft-server-util')
const token = 'bot_token'
const PREFIX = 'l.'
bot.on('ready', () => {
console.log('Bot has come online.')
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(' ')
switch (args[0]) {
case 'status':
util.status('IP', (PORT), (error, reponse) => {
if (error) throw error
const Embed = new RichEmbed()
.setTitle('Server Status')
.addField('Server IP', reponse.host)
.addField('Server Version', reponse.version)
.addField('Online Players', reponse.onlinePlayers)
.addField('Max Players', reponse.maxPlayers)
message.channel.send(Embed)
})
break
}
})
bot.login(token)
When I type node . in the console and I type l.status on the Discord server, it shows this error on the console:
(node:3300) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'options' to
be an object or undefined, got number
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:46:25
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:4:12)
at status (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:40:12)
at Object.<anonymous> (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:113:17)
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3300) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the
CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:3300) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Can anybody help? I also tried a lot of different solutions, but none of them worked.
You are using an outdatet version of discord.js. Type npm i discord.js#latest into your terminal. In the latest version of discord.js, RichEmbed() has been removed and replaced by MessageEmbed().
This is an answer based on assumption since I've never used minecraft-server-util before. Also assuming that you're using the latest minecraft-server-util,
Based on the error;
Expected 'options' to be an object or undefined, got number
And, based on this commit, You should pass the 2nd argument as an object instead of PORT since it's a type of StatusOptions instead of a number.
So, instead of;
util.status('IP', (PORT), (error, reponse) => {
You should be doing;
util.status('IP', {
port: (PORT)
}, (error, reponse) => {

I get Parser.parseErrorMessage when inserting or updating in postgres

i'm having a headache with this cause i can't understand what's the problem.
This is my code in Express
router.patch("/:id", verifyToken, async (req, res) => {
const { id } = req.params;
const { title, content, categories } = req.body;
const authorId = parseInt(req.user.id);
try {
let postId = parseInt(id);
if (postId < 0)
res.json(
utils.generateError("Something went wrong, try to reload the page.")
);
//Validate post data
const { error } = validatePostData({
title,
content,
});
//Is there and error? Let the user know it.
if (error)
res.status(400).json(utils.generateError(error.details[0].message));
const slug = await utils.generateSlug(title);
const summary = await utils.extractSummary(content, 240);
const foundImage = await content.match(/!\[.*?\]\((.*?)\)/);
let image = "";
if (foundImage) image = foundImage[1];
const result = await pool.query(
"UPDATE posts SET title=$1, slug=$2, summary=$3, content=$4, image=$5, author=$6, categories=$7 WHERE id=$8",
[title, slug, summary, content, image, authorId, categories, postId]
);
if (result) res.json(result.rows[0]);
else throw "Error on updating result";
} catch (e) {
console.log(e);
res.json(utils.generateError("Something went wrong, try again."));
}
});
But when i make a patch request i get this in the console.
(node:20756) UnhandledPromiseRejectionWarning: error: invalid input syntax for integer: "NaN"
at Parser.parseErrorMessage (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/index.js:8:42)
at Socket.emit (events.js:310:20)
at addChunk (_stream_readable.js:286:12)
at readableAddChunk (_stream_readable.js:268:9)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
(node:20756) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20756) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm using Postgres and pg for node to handle the database, the strange part is that the row is updated in the db but the result of the query doesn't return anything but that error.
Can anyone help me solve this?

How to use google-spreadsheet in nodejs

I want to use the google-spreadsheet API to fetch and write data to a sheet in my Discord bot (using discord.js). For some reason, I can't get it to work. This is my code:
const { GoogleSpreadsheet } = require('google-spreadsheet')
const creds = require('../service-account.json')
module.exports = {
/...
execute(message, args) {
accessSpreadsheet()
}
}
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('<id was here>')
doc.useServiceAccountAuth(creds)
.then(() => {
doc.getInfo()
.then(info => {
console.log(`Loaded doc: ` + info.title + ` by ` + info.author.email)
const sheet = info.worksheets[0]
console.log(
`sheet 1: ` + sheet.title + ` ` + sheet.rowCount + `x` + sheet.colCount
)
})
})
}
This is the error I keep getting:
(node:4) UnhandledPromiseRejectionWarning: Error: Google API error - [404] Requested entity was not found.
at createError (/app/node_modules/axios/lib/core/createError.js:16:15)
at settle (/app/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/app/node_modules/axios/lib/adapters/http.js:236:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I should actually use async/await for achieving this. My code has become:
async function accessSpreadsheet(message, args, msg) {
const doc = new GoogleSpreadsheet('<id was here>')
await doc.useServiceAccountAuth(creds)
await doc.loadInfo()
console.log(doc.title) //whatever you want to log goes here
})

bug in connection to cluster mongodb

i'm using nodejs to connect to mongodb and i get this error
i added the IP and nothing happend
(node:7412) UnhandledPromiseRejectionWarning: MongoNetworkError: connection 5 to cluster0-shard-00-02-xobf0.mongodb.net:27017 closed
at TLSSocket.<anonymous> (C:\Users\user\Desktop\NodeJS - The Complete Guide\node_modules\mongodb-core\lib\connection\connection.js:352:9)
at Object.onceWrapper (events.js:277:13)
at TLSSocket.emit (events.js:189:13)
at _handle.close (net.js:597:12)
at TCP.done (_tls_wrap.js:388:7)
(node:7412) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7412) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[nodemon] clean exit - waiting for changes before restart
Try this ,
const MongoClient = require("mongodb").MongoClient;
const uri ="mongodb+srv://user:userpassword#meanapp-srlw9.mongodb.net/test?retryWrites=true";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
console.log("connencted");
client.close();
});
For now, change your cluster setting to connect from anywhere

Resources