Invalid use of type "undefined" as a Firestore argument - node.js

I am getting error when I execute my code. Below code used for creating collection in cloud Firestore, before this I didn’t created any collection in cloud Firestore. It is empty. In the console.log, I am getting correct json object.
createEntry(subjectId: string, questionnaire: string, callback: (err: any, response: any) => void) :void {
let testEntity: TestEntity = new TestEntity(subjectId, questionnaire);
console.log("testEntity.toJSON();----------->",testEntity.toJSON());
var docRef = this.dbManager.collection('testQuestion').doc(subjectId);
var setAlan = docRef.set(testEntity.toJSON());
}
Here TestEntity is json values as below. All the fields have values.
public toJSON(): testEntry {
let returnJSON = {
"entry_id": this.entry_id,
"subject_id": this.subject_id,
"entry_date": this.entry_date,
"questionnaire": this.questionnaire,
"entry_start_timestamp": this.entry_start_timestamp,
"entry_end_timestamp": this.entry_end_timestamp,
"entry_complete": this.entry_complete,
"responses": this.responses,
"last_answered_question" : this.last_answered_question,
"entry_status" : this.entry_status
}
return returnJSON;
}
dbManager is this.adminInstance:
export class DatabaseManager{
private static adminInstance:any;
static getAdminInstance(): any {
if(!this.adminInstance)
admin.initializeApp(functions.config().firebase);
this.adminInstance = admin;
return this.adminInstance.firestore();
}
}
I am getting below error. How to solve it?
Error: Invalid use of type "undefined" as a Firestore argument.
at Object.exports.customObjectError.val [as customObjectError] (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/validate.js:164:14)
at Function.encodeValue (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/document.js:813:20)
at Function.encodeFields (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/document.js:683:36)
at Function.fromObject (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/document.js:223:55)
at WriteBatch.set (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/write-batch.js:301:39)
at DocumentReference.set (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/reference.js:420:8)
at testEntryService.createEntry (/user_code/services/test-entry-service.js:19:30)
at /user_code/services/intentService.js:22:36
at Function.<anonymous> (/user_code/node_modules/actions-on-google/dist/service/dialogflow/dialogflow.js:146:23)
at next (native)
Since I am new to Firebase, I am unable to identify this error. What is the root cause of the issue?

Related

TypeError: Cannot read property 'facts' of undefined

I am trying to make a word randomizer, and it gives me this error:
message.channel.send(item.facts);
^
TypeError: Cannot read property 'facts' of undefined
and I don't know how to fix it.
Here is my code:
const Discord = require('discord.js');
module.exports = {
name: 'game',
execute(message, args) {
const gameChanger = require('../text.txt')
const item = gameChanger[Math.floor(Math.random() * gameChanger.length)];
setInterval(() => {
const item = gameChanger[Math.floor(Math.random() * gameChanger.length)];
message.channel.send(item.facts);
}, 5 * 1000);
}
}
Someone please help me
The error indicates that the variable item is undefined. This is probably because you are going out of bounds of the gameChanger array, which is causing undefined to be assigned to item.

Can't get ref on realtime database with emulator

I am trying to attach a listener to realtime database on local emulator with another database selected but it's giving me a weird error.
Here is the code I am using:
const functions = require("firebase-functions");
const handler = async (snapshot, context) => {
console.log(snapshot);
console.log(context);
}
const target = functions.database
.instance("test-db")
.ref("/docs/{docID}")
module.exports = {
create: target.onCreate(handler),
update: target.onUpdate(handler),
delete: target.onDelete(handler),
}
Here is the error that I am getting:
i functions: Beginning execution of "operationsListenerRealtime-update"
! functions: TypeError: Cannot read property 'startsWith' of undefined
at new DataSnapshot (Q:\Projects\test-project\firebase\functions\node_modules\firebase-functions\lib\providers\database.js:270:44)
at RefBuilder.changeConstructor (Q:\Projects\test-project\firebase\functions\node_modules\firebase-functions\lib\providers\database.js:155:28)
at cloudFunction (Q:\Projects\test-project\firebase\functions\node_modules\firebase-functions\lib\cloud-functions.js:133:34)
at C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:592:16
at runFunction (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:579:15)
at runBackground (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:591:11)
at processBackground (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:574:11)
at invokeTrigger (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:649:19)
at handleMessage (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:736:15)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
! Your function was killed because it raised an unhandled error.
Clearly I am trying to connect realtime database that is test-db, I also tried writing http://localhost:7002/?ns=test-db but still no luck. I digged deep into the error and saw this thing:
/**
* Interface representing a Firebase Realtime Database data snapshot.
*/
class DataSnapshot {
constructor(data, path, // path will be undefined for the database root
app, instance) {
this.app = app;
if (app && app.options.databaseURL.startsWith('http:')) {
// In this case we're dealing with an emulator
this.instance = app.options.databaseURL;
}
else if (instance) {
// SDK always supplies instance, but user's unit tests may not
this.instance = instance;
}
else if (app) {
this.instance = app.options.databaseURL;
}
else if (process.env.GCLOUD_PROJECT) {
this.instance =
'https://' + process.env.GCLOUD_PROJECT + '.firebaseio.com';
}
this._path = path;
this._data = data;
}
I think the issue may be related to this part of the code
Also the instance function takes parameters like this.
EDIT: I have confirmed that with proper node version it still is giving me the same error.

TypeError: Cannot read property 'then' of null | discord.js

I am trying to make a message tracker and this error shows and I don't know why
Code: messagecounter.js
const db = require('quick.db');
module.exports = {
name: "msgc",
description: "Message Counter",
async run(client, message, args) {
// checking who wants to fetch it
let member = message.mentions.members.first() || message.member; // this checks if they mentioned a members
db.fetch(`messageSent_${member.id}`).then(obj => {
message.channel.send(`**Messages Sent:** \`${obj.value}\``);
});
}
}
Code: bot.js:70:42
client.commands.get(command).run(client, message, args);
Error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'then' of null
at Object.run (C:\Users\Familia\OneDrive\Documents\Other Stuff\Visual Studio code\blade\commands\messagecounter.js:13:45)
at Client.<anonymous> (C:\Users\Familia\OneDrive\Documents\Other Stuff\Visual Studio code\blade\bot.js:70:42)
Any help would be appreciated
Using discord.js v12
After quickly glancing over "quick.db" I couldn't find a method called fetch defined on the db object. "get", however is defined and is perhaps what you meant to use.

TypeError: Cannot read property 'EventEmitter' of undefined typescript nodejs

I have a typescript application running on node.
I am using 'EventEmitter' class to emit a change in variable value.
This is my piece of code,
import events from 'events';
public async updateStream(streamContext: string, state: boolean): Promise<string> {
const eventEmitter = new events.EventEmitter();
if (state === true) {
return StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Paused';
} else {
const streamState = StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Active';
eventEmitter.emit('resume');
return streamState;
}
}
public async waitForStreamActive(stream: Stream) {
const eventEmitter = new events.EventEmitter();
// tslint:disable-next-line:no-unused-expression
return new Promise(( resolve ) => {
eventEmitter.on('resume', resolve );
});
}
This piece of code builds fine. But when i run the code, as in execute the operation, I am getting the following error,
error: errorHandler - Apply - Hit Unhandled exception {"timestamp":"2019-04-29T12:33:49.209Z"}
error: errorHandler - Apply - Cannot read property 'EventEmitter' of undefined - TypeError: Cannot read property 'EventEmitter' of undefined
at StreamResource.updateStream (C:\Vertigo\core\reference_platform\dist\index.js:10695:51)
at StreamService.patchStream (C:\Vertigo\core\reference_platform\dist\index.js:22524:40)
at process._tickCallback (internal/process/next_tick.js:68:7) {"timestamp":"2019-04-29T12:33:49.215Z"}
What am I doing wrong?
I've set up minimal project to reproduce it and immediately ts compiler warns me about:
TS1192: Module '"events"' has no default export.
But this seems to work:
import * as EventEmitter from 'events'
new EventEmitter();

NodeJS - TypeError: Cannot read property 'name' of undefined

I am getting the following error from my code: If you could help me that would be amazing! I am using discord.js!
TypeError: Cannot read property 'name' of undefined at
files.forEach.file (/root/eternity-bot/eternity-bot/index.js:21:33) at
Array.forEach () at fs.readdir
(/root/eternity-bot/eternity-bot/index.js:18:9) at
FSReqWrap.oncomplete (fs.js:135:15)
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
console.log(`Loading Command: ${props.help.name}.`);
bot.commands.set(props.help.name, props);
props.conf.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
})
});
});
TypeError: A TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function.
The possible cause is your props is not loaded correctly and doesn't include any property help, thus accessing property name of unknown property help throws TypeError. Similar to following:
let obj = {
o1: {
a: 'abc'
}
};
obj.o1 // gives {a: 'abc'}, as o1 is property obj which is an object.
obj.o1.a // gives 'abc', as a is property of o1, which is property of obj.
obj.o2 // undefined, as there's no o2 property in obj.
obj.o2.a // TypeError as there's no o2 property of obj and thus accessing property a of undefined gives error.
What is happening is that the code is working perfectly fine, but there seems to be some problem with the exports of your javascript files in the commands folder. Most probably, the help property is not defined in your files.

Resources