Cannot delete error CRUD API (NodeJS, MongoDB, Express) - node.js

I'm getting an error while trying to delete a field from a mongo database I created in an API project I'm working on. I'm still very much new to not only RESTful APIs but also MongoDB and Express. I followed a tutorial on Youtube that explained the steps to go through to make such an API and so I did and everything worked perfectly. Now I'm trying to reproduce this API using my own custom fields.
Basically my database is populated with two elements right now. I've already created get, add and update methods that work properly. Here is the response for the get method :
[{"_id":"58a112564cb325769b9d90de","name":"John Doe","caption":"I like pizza","friends":["id1","id2","id3"],"schedule":[[13,14],[14,15.5]]},{"_id":"58a1178da52bfc07fd25ce3f","name":"Carla Doe","caption":"I hate pizza","__v":0,"friends":null,"schedule":null}]
Now the function that has an issue is the delete function. I can't seem to find what might be wrong with it. It is the exact same function as in the aformentioned Youtube tutorial. I've checked a hundred times over, there is no character wrong or missing.
Here is the error I get in postman :
Cannot DELETE /api/clients/58a1178da52bfc07fd25ce3f
Here is the server.js part :
// Delete client
app.delete('api/clients/:_id', function(req, res){
var id = req.params._id;
Client.deleteClient(id, function(err, client){
if(err){
throw err;
}
else {
res.json(client);
}
});
});
Here is the clients.js part :
// Delete Clients
module.exports.deleteClient = function (id, client, callback) {
var query = {_id: id};
Client.remove(query, client, callback);
};
I don't know if I'm giving you all the information needed to resolve the issue. I can't for the love of me find out where it's coming from.
Looking forward to read your answers.

I think a '/' is missing before '/api/clients/:_id'
it should be :
app.delete('/api/clients/:_id', function(req, res)

Related

tumblr.js createPhotoPost using multiple images url

I'm trying to user tumblr.js to create some photo post containing multiple images (from url). The method works fine when I use source (hence with a single url), but stop working when I try using data instead of source to send multiple photos at the same time.
My code is pretty basic for the moment but is still not working :
client.createPhotoPost('myblog.tumblr.com', {data: ['http://www.gstatic.com/webp/gallery/1.jpg'] },
function (err, data) {
console.log("CREATE PHOTO POST", err, data)
});
The error is API error: 401 Unauthorized which does not seem to be relevant.
Does anyone has already used this and has any idea how to fix it ?

How do I make my node express page uniqe to every new user

What I am using - EJS, JS, NODE, Express.
I am new to this and have been getting away with googling stuff so far.
So I am making a website and I want it to be unique for every new tab. Right now, if one person clicks a button that displays a message, and I go to a different tab and open the link, I can see the message that the first person set. I read something about express-session and session Id and sending the requests through the sessionID to make sure it is sent to the right person. But I don't know how to implement them here
EDIT: Here is my best attempt trying to make sense out of this.
router.post("/", (req, res, next) => {
Actors.find({}, (err, actorFound) => {
if (err) {
throw err
} else {
res.render("welcome", {
actors: actorFound,
findItems: suggested
})
}
})
})
When I "call" this on local host it would basically dump everything from the data base. Which is what it is supposed to do. However, if I open localhost using a different web browser, (trying to simulate a different visitor) I would find that my data from actors is already dumped on the page. Does this make sense. I will try to explain anything specific if you have any question and thank you very much.

MongoDB, Node, Express, EJS - Pass a array/variable from backend to frontend (from route to client)

I've been trying to figure out a better way to push a variable from the backend to the frontend. Right now I do something like this.
I have a MVC-pattern, so when hitting the route
app.get('/fil', middleWare.isLoggedIn, user.fil)
... trough node does some querying the DB, and pass on the data.
exports.fil = async (req, res) => {
try {
faktura = await Lan.find().populate('client', 'namn kundnr')
res.status(200).render('pages/createInvoice', {
faktura: faktura
});
} catch (err) {
return res.status(500).send({
message: err.message || "Some error occurred while retrieving datas."
});
};
};
... it generates the page, with the help of EJS (i love EJS) and then pass it on to the client/user.
And in the .ejs-file that is served to the client/user I add the following
<script>
var fakturor = <%- JSON.stringify(faktura) %>;
</script>
which then means that I use up the variable and work with it with JS.
And this is where my question pops up. Is this a good way to do it or is there any other way to handle it?
I guess one idea is to let the user to query the DB straight from the page, but in my case I believe it wouldn't actually be better for the user to do so (the user will reieve like 100 different rows that they will be able to filter and then download a file of)
But is there any other ways I could do this without the script-tag? Like i said, I guess a ajax-call from JS/the client could be used but could you do it any other way? Can EJS do it any other way?
ejs is used for static pages mainly, if you want to build a dynamic page I would look for a single page application framework like angular and react.
if you still want to use ejs you can use ajax call to the server to load a variable from the DB.
I would never query directly from Front end to DB because then you are not controlling the security of the server, always go through the BE.
also try to think if you really need a variable in the front end, can you solve your problem using rendering only?

Problem integrating Angular SPA and mongodb in heroku

I am creating a simple app using angular and I am trying to use mongodb to save my data. So far I managed to create my SPA with angular and deploy it to heroku adding the server.js file. My problem starts when I tried to connect mongodb.
Currently I was serving my page using
app.get('/*', function(req,res) {
res.sendFile(path.join(__dirname,'/dist/showoff/index.html'));
});
Inside index.html I am calling <app-root> and my application has two routes: /display and /control
I then realized I have to add some more routes to save and read from my database through a service, so I had to add things like:
router.route('/players').get((req, res) => {
Player.find((err, player) => {
if (err)
console.log(err);
else
res.json(player);
});
});
Problem is that I cant reach those routes since I have already one with /*. I tried writing this other routes on top as I figured it might take the first it finds but its not working and I am always redirected to my index.html
My question is:
Is there a way to deploy my SPA like this and still use mongo? or do I need to somehow restructure everything since my approach isn't right?
You can find my whole code here if needed GitHub code
In case it helps anyone I did the following. Not sure if its the best way to go but it worked.
I divided my /* route as follows
app.get('/display', function(req,res) {
res.sendFile(path.join(__dirname,'/dist/showoff/index.html'));
});
app.get('/control', function(req,res) {
res.sendFile(path.join(__dirname,'/dist/showoff/index.html'));
});
And continue to add handlers for other routes there, which manage the requests to write and read from the database.

HTTP Request doesn’t include query

I am trying to send a POST request with query parameters using the request library. I have succeded in sending these requests, but I am still unable to include any working query.
I have followed instructions from other posts and concluded that I’ve tried everything on the internet that is related to my mission.
This is the code that does comply with what I found on the internet:
const request = require(’request’);
request.post({
url: 'https://example.com/endpoint',
qs: { with_counts: true } },
function (err, res, body) {
console.log(err, body);
}
);
This, however, does not work. The server does not recieve the query. I tried setting the body and json properties instead, but those didn’t work either.
I cant tell what I’m doing wrong, and I realize that it might not be possible for you to tell, but this is my last desperate attempt before giving up and switching to Python.

Resources