How to add conditional checks over ORM (sequelizejs) queries? - javascript

Suppose i have a table gameData {gameId, currentBoardLayout}, a get request like www.chess.com/asd123 is sent over to the server, where asd123 is my game id, I need to catch this id (asd123 which is my gameId) and check for it in my table (gameData) and implement the following logic :
srv.get('/:id', (req, res) => {
if ( gameData.findAll({where: {gameId: req.params.id} )
{ // Game room found
return currentBoardLayout
}
else
{ error : Invalid game id }
})
How can I achieve this?
Thanks

You can use Sequelize's findById method.
srv.get('/:id', (req, res) => {
gameData.findById(req.params.id)
.then(result => {
res.send(result)
})
.catch(() => {
res.send({
error: 'Could not find ID'
})
})
})
Here's what is happening:
Sequelize's findById method will return a promise. If it successful, you will get your item from the database back. If the item cannot be found, the catch method will fire.
res.send is Express' way of sending data back to the client.
It is worth checking out the Sequelize docs:
Using models
Querying

Related

filled array is empty when send back to user

I try to get data from an azure database with SQL and for this I use tedious. When I execute the code, the array "result" gets filled up with data but when de respond sends the array "result" to the user it is empty. Why and how can I solve it? (I want to send it back in JSON format, the legth is unknown I use 5 to debug).
This is my code
router.get('/', async (req, res) => {
result = []
let rowData = {}
const request = new Request(
`SELECT TOP (5) [LogID]
,[OpdrachtID]
,[ChangeLog]
,[TimeStamp]
,[PersonID]
FROM [log].[LOpdracht]`,
function (err, rowCount, rows) {
if (err) throw err
})
connection.execSql(request)
request.on('row', function(columns){
rowData = {}
columns.forEach(function(column){
rowData[column.metadata.colName] = column.value
})
result.push(rowData)
})
res.send(result)
})
Looks like you are using Tedious. If that is so then you can use the 'done' event to be notified when the request has completed and all rows have been read into result.
request.on('done', () => res.send(result));
Update: As the note in the documentation points out, since you are using execSql you will need to listen to doneProc and doneInProc instead:
request.on('doneProc', () => res.send(result));
request.on('doneInProc', () => res.send(result));
I solved it by adding this:
request.on('requestCompleted', () => {
res.send(result)
})

'TypeError: Converting circular structure to JSON' with Express

I use NodeJS and Express for my project and set it when the user login to index will keep the session value.
req.session.user
{ adminID: 3, username: 'admin', password: 'admin' }
And I want to get data from MYSQL so I use Knex like this.
router.get('/profile/user/me', (req, res, next) => {
let user = req.session.user;
if(user) {
try {
let me = req.session.user.adminID;
let info = knex('admin_account').where('adminID', `%${me}%`)
res.json(info)
} catch (e) {
console.log(e);
}
res.sendFile(path.join(__dirname + '/../public/personal_information.html'));
return;
}else{
res.redirect('/');
}
});
In my opinion, I think that if we are finished logging in, we will have a req.session.user I will use it to get data together with Knex.
req.sessions.user and info may have the same value but arent the same type you should, first check the value of your variable info console.log(info), there is a chance that you might need to json.parse() it or json.stringify() it if you want to send it as a response.
You need to execute the query builder and wait for result before returning:
knex('admin_account').where('adminID', me)
.then(info => {
res.json(info)
})
.catch(err => {
console.log(e);
});
And you don't need % wildcards unless you are doing loose string comparison with like operator.
One more thing about the code is that you seem to try to return res.json and also res.sendFile(path.join(__dirname + '/../public/personal_information.html')) at the same time, which doesn't make sense.

How to delete data from database and UI using react.js and axios?

I am trying to delete data from my app both in the database and UI, but I am a
bit confused on how to request this action from react.js using axios. I have
created a method call which I assigned to an event handler on the elements
'delete' button within my react app but continue to get a message of 'null' in
the terminal. I suppose this is the app telling me that it cannot find the
element I am trying to delete and would greatly appreciate it if someone could
point me in the right direction or give me some pointers on how to fix errors I
may have made along the way.
Below is my react code
state = {
title: '',
body: '',
posts: []
}
deleteBlogPosts = () => {
axios.delete(`/api/delete`)
.then((response) => {
console.log(`${response} request deleted`)
})
.catch((err) => {
console.log(err.response)
})
}
displayBlogPosts = (posts) => {
if(!posts.length) return null
return posts.map((post, index) => (
<div className='blog' key={index}>
<h1>{post.title}</h1>
<h5>{post.body}</h5>
<button onClick={this.deleteBlogPosts()}>delete</button>
</div>
))
}
MY API file with the endpoints
router.delete('/delete', (req, res) => {
Blog.findOneAndRemove({
_id: req.params.Id
}, (err, data) => {
console.log(data)
if(err) {
res.status(500).json({
msg: 'Houston we have a problem'
})
return
}return res.json({
msg: 'Data was received'
})
})
})
Hey everyone thanks for those who attempted to help. Shortly after posting, I realized that I had unnecessary parameters within my 'delete' endpoint. I also found out that I failed to include the ID in the endpoint URL. SO happy that I got it taken care of.

I can`t delete anything from my MongoDB [duplicate]

I'm currently working on my first node.js rest api with express, mongodb (atlas cloud) and mongoose, when i try to make a .remove request i get this error:
{
"error": {
"name": "MongoError",
"message": "Cannot use (or request) retryable writes with limit=0",
"driver": true,
"index": 0,
"code": 72,
"errmsg": "Cannot use (or request) retryable writes with limit=0"
}
This is my request:
router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
}); ;
});
The findOneAndRemove() function would work more accordingly since its specific to the filtering method passed in the function .findOneAndRemove(filter, options) to remove the filtered object. Still, if the remove process is interrupted by the connection the retryRewrites=true will attempt the execution of the function when connected.
More information here
When using retryRewrites set to true tells the MongoDB to retry the same process again which in fact can help prevent failed connections to the database and operate correctly, so having it turn on is recommended.
More info here
If you are using Mongoose 5^ and MongoDB 3.6 your code is better written like:
mongoose.connect('mongodb.....mongodb.net/test?retryWrites=true', (err) => {
if(err){
console.log("Could not connect to MongoDB (DATA CENTER) ");
}else{
console.log("DATA CENTER - Connected")
}
});// CONNECTING TO MONGODB v. 3.6
router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.findOneAndRemove({ _id: id })//updated function from .remove()
.exec()
.then(result => {
res.status(200).json({
message: "Product Removed Successfuly"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
}); ;
});
I just changed the true to false in retryWrites=true and it worked. Is that a good approach? Or there is a better way to solve this problem?
retryWrites=true is a good thing, a workaround for this incompatibility is to use findOneAndRemove instead of remove (looks like you're using mongoose)

error: syntax error at or near "$"

I am currently checking out Vue and am doing a little refactor on a personal project.
I am running into some problems with my API.
The two technologies involved are axios which I am using to send requests to my API, which talks to a postgres database using pg-promise.
The api call...
function add (entry, cb) {
const length = entry.content.length
entry.title = `${entry.content.substring(0, 32)}`
axios.post('/api/notes', entry).then(cb)
}
here, entry is and object { title, content, prio, status, context }
the pg-promise endpoint
export const createNote = (req, res, next) => {
db.none('insert into entries(title, content, prio, status, context)' +
'values( ${title}, ${content}, ${prio}, ${status}, ${context})',
req.body)
.then(() => {
res.status(200)
.json({
status: 'success',
message: 'Inserted one entry'
})
}).catch(err => next(err))
}
here, req.body is undefined
I don't know why I am getting undefined.
Does this error log help?
I was reading through the documentation at axios and could not seem to find anything wrong with my api call, figured I would post something here.
Thanks!
req.body It has the following structure [{.....}]
for pg-promise need {....}
Solution to the problem req.body[0]
export const createNote = (req, res, next) => {
db.none('insert into entries(title, content, prio, status, context)' +
'values( ${title}, ${content}, ${prio}, ${status}, ${context})',
req.body[0])
.then(() => {
res.status(200)
.json({
status: 'success',
message: 'Inserted one entry'
})
}).catch(err => next(err))
}

Categories

Resources