ExpressJS res.json(data of the logged in user) - json

I'm building and MEAN stack APP.
exports.show = function(req, res) {
Posts.findById(req.params.id, function (err, post) {
if(err) { return handleError(res, err); }
if(!post) { return res.send(404); }
return res.json(post);
});
};
Can someone explain how can I send just the posts of the logged in user?
Note: post has a author key equal with the user ID

You should probably look to use the req.user property (I assume you're using Passport or something similar):
exports.show = function(req, res) {
Posts.find({author: req.user.id}, function (err, posts) {
if(err) { return handleError(res, err); }
if(!post) { return res.send(404); }
return res.json(posts);
});
};
If req.user.id doesn't work, try console.log() on req.user, and see if it contains the information you need.

Related

Mongoose updating and fetching in the same request

I have the following mongoose "update" path:
app.put('/update', async (req, res) => {
const newTaskName = req.body.todoName
const newDays = req.body.days
const id = req.body.id
try {
await TodoModel.findById(id, async (err, updatedTodo) => {
updatedTodo.todoName = newTaskName
updatedTodo.daysToDo = newDays
await updatedTodo.save()
res.send("updated")
})
} catch(err) {
console.log(err)
}
})
Separately I have a path that returns all data from the Mongo table:
app.get('/read', async (req, res) => {
TodoModel.find({}, (err, result) => {
if (err) {
res.send(err)
}
res.send(result)
})
})
How can I both update and send back the full updated list within the response?
Separate question, not necessary to answer, but would be nice - perhaps this approach is all wrong? some background:
In my MERN app I am calling to add an item to a list and then want to immediately render the updated list as currently read from the database, since I don't want to assume the insertion was successful
I tried using some asynchronous workarounds with no luck
Fixed!
Upon further inspection of Mongoose documentation, I found that by using the findOneAndUpdate method instead of findById, I am able to utilize a callback that will return the updated item:
app.put('/update', async (req, res) => {
const id = req.body.id
let updateSet = req.body
delete updateSet.id
try {
ShoppingModel.findOneAndUpdate({ _id: id }, { $set: updateSet }, { new: true }, (err, doc) => {
if (err) return console.log(err)
res.send(doc)
})
} catch (err) {
console.log(err)
}
})

Nodejs Mysql asynchronous

I'm trying to return my users list from my Mysql database through this endpoint.
The problem is that it return "undefined".
Do you know how to solv this?
Thx in advance :)
app.get("/users", async (req, res) => {
users = await query_my_users_from_db()
// Got "users = undefined" here
console.log(users)
return JSON.stringify(users)
})
async function query_my_users_from_db() {
var users = await db.query("SELECT * FROM `users`", function (err, result) {
if (err) throw err
users = Object.values(JSON.parse(JSON.stringify(result)))
return users
})
}
Since db.query is callback based, you should change your code into:
function query_my_users_from_db(callback) {
db.query("SELECT * FROM `users`", callback)
}
remove all the async\await since you are not using any promises!
then define your callback
const usersHandler = (err, result) => {
... do what you want with your users ...
}
and use it like this:
query_my_users_from_db(usersHandler)
Another option is to use some promise-based wrapper package for MySQL, there is plenty or use node util.promisify() (https://www.geeksforgeeks.org/node-js-util-promisify-method/) and then use async\await and remove the callback altogether.
Hope that it helps
I used this and it's working like a charm.
db.promise = (sql, params) => {
return new Promise((resolve, reject) => {
db.query(sql, params, (err, result) => {
if (err) {
reject(new Error())
} else {
resolve(result)
}
})
})
}
async function connection(query) {
const result = await db.promise(query)
return result
}
app.get("/users", async (req, res) => {
users = await connection("SELECT * FROM `users`")
return users
})

How can I condition my router details to show me all the id's?

In this router it managed to show only a specific id, but within that id I would like to show the others that I have in my database.
router.get('/detalles/:id', (req, res) => {
const id = req.params.id;
conexion.query('SELECT * FROM noticias WHERE id=?', [id], (error, results) => {
if (error) {
throw error;
} else {
res.render('detalles', { noticias: results[0], results: results });
}
});
});
At the top I only need the details of a specific id, below I want to show the others.
What I would recommend you is to do a "Get All" route which means that you will take every id. It think it will look like this.
! Warning ! Don't forget to put it before you route '/detalles/:id' to avoid conflict between them so it will not call /detalles/:id without any id.
router.get('/detalles/', (req, res) => {
conexion.query('SELECT * FROM noticias', (error, results) => {
if (error) {
throw error;
} else {
res.render('detalles', { noticias: results, results: results });
}
});
});

Returning undefined from mySQL

I know the database is connecting with the code as, when i console.log(res) with the code below it is returning the correct data,
const orm={
selectAll(){
connection.query('SELECT * FROM burgers', (err,res) => {
if (err) throw err;
console.log(res)
return res;
});
},
Yet when i console.log(burgers) from this function in the code below it is returning an undefined
app.get(`/`, function (req, res) {
const burgers = orm.selectAll();
console.log(burgers)
res.render(`index`, burgers);
});
I understand this may be a very simple answer but i personally just cannot work it out any help is welcomed.
selectAll is using a callback style method inside it. You can not get the response syncronously. You need to either pass the callback to selectAll or change it to use promise like this
function selectAll() {
return new Promise((reoslve, reject) => {
connection.query("SELECT * FROM burgers", (err, res) => {
if (err) {
reject(err);
}
reoslve(res);
});
});
}
You can then use it like this
app.get(`/`, function async (req, res) {
const burgers = await selectAll();
console.log(burgers)
res.render(`index`, burgers);
});
Your selectAll method will not return any value.
query get an lambda callback function as second parameter AND query is asyncron
One way is to return an Promise from selectAll
const orm = {
selectAll(callback) {
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM burgers', (err, res) => {
if (err) {
reject(err);
} else {
resolve(res)
}
})
})
},
Than you can get your result:
app.get(`/`, function (req, res) {
orm.selectAll().then( burgers => {
console.log(burgers)
res.render(`index`, burgers);
});
});

Can't get data by id using NodeJS and MySQL

I am new to NodeJs and I want to get some information by id. Here is my code The controller :
router.get('/machine', function (req, res) {
Machine.getmachine(req.body, function (err, row) {
if (err) {
res.status(400).json(err);
}
else {
res.json(row);
}
});
});
The SQL part :
getmachine: function (Machine, callback) {
return db.query('SELECT * from machine WHERE id=?', [Machine.id], callback);
},
I tried to test it with Postman and I only got {} as a result.
Please, can you tell me why I don't get what I want?
Try something like this instead of reading the body data you should read it as query. or else if you are passing as params you should user req.params('id') to get the id.
router.get('/machine', function (req, res) {
Machine.getmachine(req.query.id, function (err, row) {
if (err) {
res.status(400).json(err);
}
else {
res.json(row);
}
});
});
Edit
According to the url you provided in the comment you can try something like this.
router.get('/machine:id', function (req, res) {
Machine.getmachine(req.params.id, function (err, row) {
if (err) {
res.status(400).json(err);
}
else {
res.json(row);
}
});
});
If you managed to get the id to the back-end then the issue must be with in you sql query. try something like this
getmachine: function (Id, callback) {
return db.query('SELECT * from machine WHERE id=?', Id, callback);
}