I'm using firebase-admin v11.2.1
I can update a title in a project using:
if (title) {
batch.update(projectRef, {
title
})
}
But I cannot add an item to an array using:
batch.update(projectRef, {
admins: admin.firestore.FieldValue.arrayUnion(`/users/${admin}`)
})
The error is being caught in a catch block, but the error comes back as an empty object
} catch (err) {
res.status(500).json({ error: err })
}
resolves as:
{
"error": {}
}
Everything I read doing what I want to do point to arrayUnion as the answer, but it's not working for me. Any help is appreciated - thank you.
Edit: Here is the way a project is modeled.
I'm on another codebase too where arrayUnion is NOT working. I get the error:
const ids = members.map((member) => member.id);
await projectRef.update({
members: admin.firestore.FieldValue.arrayUnion(...ids)
)}
error TypeError: Cannot read properties of undefined (reading 'arrayUnion')
Though I'm in another codebase where arrayUnion is working exactly like you'd expect (firebase-admin version 9.8):
if (role === 'admin') {
batch.update(organisationRef, {
invitedAdmins: admin.firestore.FieldValue.arrayUnion(userId)
})
}
So very stumped 🤔
const { FieldValue } = require('firebase-admin/firestore');
FieldValue.arrayUnion(userId)
Related
I have been playing around with ExpressJS I normally use FastAPI. I can't seem to generate an error using Supabase.
I have this endpoint
app.delete('/api/delete-book/:id', cors(corsOptions), async (req, res) => {
const {data, error} = await supabase
.from('books-express')
.delete()
.match({id: req.params.id})
if (error) {
res.status(400).send({message: `ERROR! ${error.message}`})
}
if (data)
res.send({
message: `Book ID ${req.params.id} has been deleted from the database`,
})
})
This works when it comes to deleting a book via an ID. However if I enter an invalid ID I get the data if block firing.
There is no book with an ID of 222 in the database, I would expect the error to fire but its just null
Any ideas here?
This is expected behaviour; not matching any rows is not considered an error condition in postgres.
If you'd like to check if any rows were deleted, you can use something akin to (on supabase-js 2.x):
const { data, error } = await supabase.from('books-express')
.delete()
.match({id: req.params.id})
.select() // not needed on 1.x libs
if (error || data.length === 0) {
res.status(400).send({...})
}
I have got a function in a service that needs to get a value of a new or already existing object from the database and save it.
Issue is that name attribute of this object needs to be unique.
I know i can just create a .some() function over all database objects to check if i can enter this new value but its probably very unoptimal.
I would like to create somethign like this (below) but i have no idea what to do next:
const newObject = await this.repository
.save({
...newObjectDto,
})
.catch(err => {
if (err instanceof QueryFailedError) {
// some code for err checking to make
// sure i only catch the unique_violation
// error and then throw error
}
});
Error code for unique_violation is 23505. You can check out the full list of error codes returned by PostgreSQL here.
In order to catch a unique constraint violation, you can do:
try {
const newObject = await this.repository
.save({
...newObjectDto,
})
}
catch(err) {
if (err instanceof QueryFailedError) {
if(err.code === '23505') {
console.log(`Unique constraint ${err.constraint} failed`);
throw err;
}
}
}
I have a cloud function which is being executed successfully but it only returns a null value as a response to my app. In Firesbase console it only shows this message:
Function execution took 1438 ms, finished with status code: 200
Exception from a finished function: Error: Cannot read properties of
undefined (reading 'firestore')
I receive null in my client app:
data: null
I googled the error message but no one seemed to have posted something like this anywhere.
I have tried placing my code inside try catch but it seems to not catch the error or whatever is happening there. I am stuck at this point, dont really know what else to do in order for me to understand what's going on. My biggest bet is that the geotransaction.get() is not accepting the collection reference.
below is how I include the needed modules:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const firestore_ = admin.firestore();
const GeoPoint = admin.firestore.GeoPoint;
const FieldValue = admin.firestore.FieldValue;
const _geofirestore_ = require("geofirestore");
_geofirestore_.initializeApp(firestore_);
and below is my function code:
const longitude = data.longitude;
const latitude = data.latitude;
const thirty_mins_old = data.thirty_mins_old;
const currenttime = data.currenttime;
try {
const GeoFirestore_ = new _geofirestore_.GeoFirestore(firestore_);
const sfDocRef = GeoFirestore_.collection('chats')
.limit(1)
.near({ center: new GeoPoint(latitude, longitude), radius: 1 })
.native.where("created", ">=", thirty_mins_old)
.orderBy("created", "desc");
GeoFirestore_.runTransaction((transaction) => {
const geotransaction = new _geofirestore_.GeoTransaction(transaction);
return geotransaction.get(sfDocRef)
.then((sfDoc) => {
if (!sfDoc.exists) {
return 'doesnt exists';
} else {
return 'exists';
}
}).catch((error) => {
throw new functions.https.HttpsError('internal', error.message);
});
});
} catch (error) {
throw new functions.https.HttpsError('internal', error.message);
}
} catch (error) {
if (error.type === 'UnauthenticatedError') {
throw new functions.https.HttpsError('unauthenticated', error.message);
} else if (error.type === 'NotAnAdminError' || error.type === 'InvalidRoleError') {
throw new functions.https.HttpsError('failed-precondition', error.message);
} else {
throw new functions.https.HttpsError('internal', error.message);
}
}
500 is a http error response to a request:
500 Internal Server Error
This error use to have many causes thus becoming hard to find why it happened, you can debug and analyse the debugging.
Although, the http status code 200 shown in your firebase console means success:
200 OK
I don’t know if this would help or not but have you tried importing the admin sdk like: import * as admin from "firebase-admin"; ?
I don't see anything in here that waits for the transaction to finish, or does anything with the result of it. Try putting return in front of GeoFirestore_.runTransaction.
I am write API in expressjs with Sequence. But I got problem with return value when update!
I follow a tutorial on internet but it got error when num=[1] not num=1 although updating success!
exports.update = (req, res) => {
const { id } = req.params;
Post.update(req.body, {
where: { id }
})
.then((num) => {
if (num === 1) {
res.send({
message: 'Post was updated successfully.'
});
}
else {
res.send({
message: `Cannot update Post with id=${id}. Maybe Post was not found or req.body is empty!`
});
}
})
.catch((err) => {
res.status(500).send({
message: `Error updating Post with id=${id}`
});
});
};
So, what return value after call update method? and how do I solve it? Thanks.
The sequelize document of update is
public static async update(values: object, options: object): Promise<Array<number, number>>
Promise<Array<number, number>>
The promise returns an array with one or two elements. The first element is always the number of affected rows, while the second element is the actual affected rows (only supported in postgres with options.returning true).
So, it will not return only the number. you need to follow the document.
To resolve
.then((nums) => {
const num = nums[0]
.....
I want to capture the E11000 duplicate key error, so I deliberately insert the same user(uid is the key)
const MongoError = require('mongodb-core').MongoError
async function insertUser(uid) {
try {
await userModel.create({
"uid": uid,
"create_datetime": new Date(),
})
} catch (e) {
console.log(e.constructor)
console.log(e instanceof MongoError)
}
}
Using the Debugging tool, I can see the constructor of e is class MongoError extends Error, however the result of e instanceof MongoError is false, very strange!! anyone good advice?
I don't think this answers your actual question, but I don't believe the errors are meant to be caught like this.
Rather, you should check if
error.name==='MongoError' && error.code === 11000
which is the recommended solution of Valeri Karpov, one of the core mongoose developers himself: https://thecodebarbarian.com/mongoose-error-handling
(the article is from 2016, but I still believe it to be valid)
It seems on the MongoDB documentation that it is the good way to handle the errors (see official doc link below).
But on my side I don't even succeed to require MongoServerError, I got "MongoServerError is undefined". I installed MongoDB NodeJS Driver with "npm i mongodb" but I also have mongoose installed and I connect to a remote Atlas mongodb server. Do you know how I should require MongoServerError?
https://mongodb.github.io/node-mongodb-native/4.3/index.html#error-handling
const client = new MongoClient(url);
await client.connect();
const collection = client.db().collection('collection');
try {
await collection.insertOne({ _id: 1 });
await collection.insertOne({ _id: 1 }); // duplicate key error
} catch (error) {
if (error instanceof MongoServerError) {
console.log(`Error worth logging: ${error}`); // special case for some reason
}
throw error; // still want to crash
}