What return value of sequelize when update? - node.js

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]
.....

Related

Supabase & ExpressJS having issues with errors

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

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,
});

How to count URL visit in Nodejs , express?

I am trying to make this basic CRM and here i need to see how many times the link has been visited by the client! is there any way i can do that and store ?
Actually I did this, as Ravi Teja said comment.
Added userClicks in the database model in case of mongoose.
(This is nested into another object)
analytics: {
userClicks: {
type: Number,
default : 0
}
}
When any request hits to that URL, I just update that count by one.
app.get('URL', (req, res) => {
//First find document in database
Url.findOne({
$text: {
$search: request.params.shortUrl
}
}).then(url => {
if (url === null) {
return response.status(404).json({
message: "Link in not valid"
});
} else {
//If successfully found, get already stored value and updated with +1, and then update that document.
const _id = url._id
let counterClicks = url.analytics.userClicks;
//Update existing values
counterClicks++;
Url.findByIdAndUpdate({
_id
}, {
$set: {
'analytics.userClicks': counterClicks
}
}).exec().then(url => {
console.log(url);
return response.redirect(302, url.originalUrl);
}).catch(error => {
console.log(error);
});
}
}).catch(error => {
console.log(error);
});
});
You can do this by newer async-await syntax.
From the above's code snippet, we will get idea, How to implement it.

How do I toggle boolean values in JSON object using express?

I am a beginner and have just finished my first MERN CRUD app. I've thought about a few ways to improve the app. The app is a todo list and has a complete button. The complete button will score a line through an item in the todo list. The complete button triggers a function which will make a post request (shown below) to the nodejs/express backend server. When the "isCompleted" field in the Mongo model is set to "true" (by default it's false), the item will be scored out. I tried to find a way to toggle the boolean values in the "isCompleted" field, whenever the complete button is clicked. This way you can unscore an item. But I just couldn't figure out how to implement this. Any ideas?
exports.updateEntry = async (req, res, next) => {
try {
const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: true});
return res.status(200).json({
success: true,
data: entry
});
} catch (err) {
return res.status(500).json({
success: false,
error: 'Server Error'
});
}
before the
const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: true});
you need to fetch the current value of the variable, should be something like this (been a long time since i worked with mongo):
const isCompleted = await Entry.findById({_id:req.params.id}).select('isCompleted')
then use !isCompleted to get the toggled value, like this:
const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: !isCompleted});
You can use body-parser middleware at top of your function (maybe you need it at a general level, so you can use it at index.js of your express project).
Then you can do this:
exports.updateEntry = async (req, res, next) => {
try {
const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: req.body.isCompleted});
return res.status(200).json({
success: true,
data: entry
});
} catch (err) {
return res.status(500).json({
success: false,
error: 'Server Error'
});}

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].

Resources