Supabase & ExpressJS having issues with errors - node.js

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({...})
}

Related

express.js mongdb its showing data for the wrong call

I am trying to get data from data base for a certain creator or user, but it shows data even if the creator doesn't exists.
this is the code
app.use('/api/places', placesRoutes);
router.get('/user/:uid', placesControllers.getPlacesByUserId);
const getPlacesByUserId = async(req, res, next) => {
console.log("request data!", req.params.uid);
const userId = req.params.uid;
let places;
try {
places = await Place.find({ creater: userId });
} catch (err) {
const error = new HttpError('Something went wrong, could not find a place for the given user.',500);
return next(error);
}
if(!places || places.length === 0){
return next(new HttpError('Could not find a place for the provided userid.',404));
}
res.json({ places: places.map( place => place.toObject({ getters: true }) ) });
};
this the data entry saved in mondo db
{"_id":{"$oid":"62ab10baa6f33b1c588dfb8e"},"title":"ifel tower","description":"big tower","image":"https://pixabay.com/images/search/nature/","address":"Circular Rd, Walled City of Lahore, Lahore, Punjab 54000, Pakistan","location":{"lat":{"$numberDouble":"31.5924979"},"lng":{"$numberDouble":"74.3073198"}},"creator":"u1","__v":{"$numberInt":"0"}}
it should only show data on this url
api/places/user/u1
but it show the same data on different creator id's
data with different url
I think it's related to the typo in the following line:
places = await Place.find({ creater: userId });
I guess creater should be creator instead.

How to do 2 or more "FIND" (mongo) request in node in the same route?

I´m new to Node, Mongo and ReactJS, and I´m trying to show all the documents in my collections in the same page. But I don´t know how to call the FIND methods and which what route use, because it has to be shown in the same page. This is the code I have so far.
app.get("/home",(req,res)=>{
JobModel.find({},(err,result)=>{
if(err){
res.json(err);
}else{
res.json(result);
}
});
});
app.get("/home",(req,res)=>{
SchoolModel.find({},(err,result)=>{
if(err){
res.json(err);
}else{
res.json(result);
}
});
});
Also, like the information from the schools and jobs are almost the same (except for the name, they both have date and desciption, just the name attribute changes) the information of the jobs are duplicated but with diferent style and with no name shown(because I changed the style between them to identificate them)
You can also use the new async syntax to solve.
Your code would be like this.
app.get("/home", async (req, res) => {
const jobData = await JobModel.find().exec();
const schoolData = await SchoolModel.find().exec();
res.json({
jobData,
schoolData
})
});
There may be many approache that you have, I think a simple one is to use promise.all function in node.js
const promise1 = JobModel.find({}).exec();
const promise2 = SchoolModel.find({}).exec();
Promise.all([promise1, promise2]).then(values =>
{
console.log(values[0]) // job docs
console.log(values[1]) // school docs
res.json(values)
}
).catch(err => console.error(err))

deleteMany only returns 1 value deleted in change streams

I have a deleteMany request but I am having a hard time in filtering my context of the deleteMany returned value. It only returns 1 value deleted from pusherjs.
Here is my change stream code and pusher code in server side;
if (schedules.operationType === 'delete') {
const scheduleDetails = schedules.documentKey;
pusher.trigger('schedules', 'deleted', {
_id: scheduleDetails._id,
teamOne: scheduleDetails.teamOne,
teamTwo: scheduleDetails.teamTwo,
user: scheduleDetails.user,
isDone: scheduleDetails.isDone,
isStarted: scheduleDetails.isStarted,
date: scheduleDetails.date,
gameEvent: scheduleDetails.gameEvent,
});
}
Here is my pusher code in client side. I am using React by the way. It is stored in my context api;
ScheduleChannel.bind('deleted', ({ deletedSchedule }) => {
console.log(deletedSchedule);
setScheduleList(
scheduleList.filter((schedule) => schedule._id !== deletedSchedule._id)
);
});
here is my code on request;
exports.deleteallmatch = async (req, res) => {
try {
const { sub } = req.user;
const deletedMatches = await Schedule.deleteMany({ user: sub });
return res.status(201).json({
message: 'All of your schedule is successfully deleted!',
deletedMatches,
});
} catch (err) {
return res.status(400).json({
message: 'Something went wrong.',
});
}
};
The delete request is fine but I want to have realtime in my app. Cuz it happened that only one data is being send instead of many. How can I solve this?
The deleteMany() method returns an object that contains three fields:
n – number of matched documents
ok – 1 if the operation was successful
deletedCount – number of deleted documents
What you can do is:
First find all elements that match your query
Store them in some variable
Perform deleting
Return the stored variable
let deleted_items = await Schedule.find({ user: sub });
await Schedule.deleteMany({ user: sub });
return res.status(201).json({
message: 'All of your schedule is successfully deleted!',
deleted_items,
});

Express application cannot get certain item from my database (Sqlite)

I am creating an application in which users can create posts and comment on these. Creating, updating and deleting posts works as intended, and so does creating comments.
When the user creates a comment, its accountId is passed to the database.
When deleting a specific comment, the accountId is passed to verify that the user is allowed to delete it.
The problem is, it seems like the accountId isn't fetched from the database, though the query asks for all details from the database table called "comments".
The app is divided into two files, db.js, and app.js.
I have tried modifying the request. In order to troubleshoot, I added a line of code checking if the comment.accountId was fetched, but that is where I get the error.
/* in db.js: */
//get comment by comment id
exports.getCommentById = (id, callback) => {
const query = 'SELECT * FROM comments WHERE id = ?'
const values = [ id ]
db.all(query, values, (error, comment) => {
if (error) {
console.log(error)
callback(['databaseError'])
return
} else if (!comment) {
console.log(error)
callback(['notFound'])
return
} else {
callback([], comment)
}
})
}
/* in app.js */
app.delete('/comments/:commentId', (req, res, next) => {
const commentId = req.params.commentId
db.getCommentById(commentId, (errors, comment) => {
if (errors.length > 0) {
res.status(500).json({
message: 'serverError'
}).end()
return
} else if (!comment) {
res.status(404).json({
message: 'notFound'
}).end()
return
}
const accountId = req.accountId //from my auth middleware
const commAccId = comment.accountId
if(!commAccId) {
console.log(accountId)
console.log(commAccId)
res.status(404).json({
message: 'AccIdNotFound'
}).end()
return
}
- - - - - ^ this is the error checking I inserted, and this is where the error is thrown, so it seems like the id is just not found.
if(!accountId) {
res.status(401).json({
message: 'notAuthenticated'
}).end()
return
} else if (comment.accountId != accountId) {
res.status(401).json({
message: 'notAuthorized'
}).end()
return
}
//plus code for deletion (will insert if it seems relevant, just ask)
})
})
The error message is "AccIdNotFound"
console.log returns 5 (same as the logged in user) and undefined
db.all delivers an array of rows, not just one row. You are assuming the result is a single comment only.
You should check result.length, then pull out result[0].

Can't bind params in nodejs

I want to bind params in node js and this is my code but shows some erros,
app.get("/single/:id", async (req, res) => {
let id = req.params.id;
console.log(id);
try{
const singleMovie = await Movies.findById(id)
res.render("single", {
singleMovie: singleMovie
});
}catch(err){
console.error(err.message);
}
});
shows me this warning,
Cast to ObjectId failed for value "undefined" at path "_id" for model
"Movies" and id is undifined
any way to fix this?
In your code res.render("single", { should be res.json("single", {
Try the code below... sending the response in json just to test it....
if you get the same error you are getting, then there is a problem somewhere in your code. Because The block of code you posted looks fine!
app.get("/single/:id", async (req, res) => {
let id = req.params.id;
console.log(id);
try{
const singleMovie = await Movies.findById(id)
res.json({
singleMovie: singleMovie
});
}catch(err){
console.error(err.message);
}
});
Also make sure you are using nodejs -v 8+ and mongoose -v 5+

Resources