Nodejs Rest API with mongoose and mongoDB - node.js

I have this rest API on nodejs as follows
router.route('/api/Customers')
.post(function(req, res) {
var Customer = new Customer();
Customer.name = req.body.name;
Customer.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Customer created!' });
});
})
.get(function(req, res) {
Customer.find(function(err, Customers) {
if (err)
res.send(err);
res.json(Customers);
});
});
router.route('/api/Customers/:Customer_id')
.get(function(req, res) {
Customer.findById(req.params.Customer_id, function(err, Customer) {
if (err)
res.send(err);
res.json(Customer);
});
})
.put(function(req, res) {
Customer.findById(req.params.Customer_id, function(err, Customer) {
if (err)
res.send(err);
Customer.name = req.body.name;
Customer.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Customer updated!' });
});
});
})
.delete(function(req, res) {
Customer.remove({
_id: req.params.Customer_id
}, function(err, Customer) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
How can I create endpoints for specific fields ? For example if I want to GET results for CustomerName, CustomerZip, etc .. Do I have to create separate end points for each field?

Are you using express.js as framework? In this case you can put optional params in your route, for example:
router.route('/api/Customers/:Customer_id?')
.post(function(req, res) {
...
})
.get(function(req, res) {
...
});
});
in this way :Customer_id will be optional and you can manage logic inside your route.
This is a working example:
app.route('/test/:param1?/:param2?')
.get( function(req, res, next) {
res.json({
'param1' : req.params.param1,
'param2' : req.params.param2
});
});
app.listen(8080);
this route supports:
/test
/test/1
/test/1/2
inside response you can see value of this params, I don't know how pass only param2 without param1.

Related

express js URL cleanup

I create a rout that get user full details from the DATABASE(mongoDB).
Router
router.get('/user/:userid/:name', getUrl, function(req, res, next) {
User.findOne({_id: req.params.userid})
.exec(function(err, user) {
if (err) { return next(err); }
if (!user) { return next(404); }
res.render('........');
});
});
for instance i can access this router with this URL:
http://127.0.0.1/user/6465667/username
but what i realy want is this
http://127.0.0.1/user/username
Is there a way of hiding the user ID in the URL
Simply remove :userid from your route and use the name to lookup your database. Ensure your username is unique otherwise you might receive the wrong user details.
router.get('/user/:name', getUrl, function(req, res, next) {
User.findOne({name: req.params.name})
.exec(function(err, user) {
if (err) { return next(err); }
if (!user) { return next(404); }
res.render('........');
});
});

PassportJS: Edit user info

I'm using PassportJS. I'm trying to let users edit their email address if needed. This is the code I have which is currently not working.
Any advice? Thank you!
app.post("/editprofile", middleware.isLoggedIn, function(req, res, next){
User.update({ id: req.session.passport.user }, {
email: req.body.email,
}, function(err, user) {
if (err) return next(err);
User.findById(req.user._id, function(err, user) {
if (err) return next(err);
console.log(err)
return res.render('landing.ejs', {
user:user
});
});
});
});
Consider using this and every thing will be fine
app.post("/editprofile", middleware.isLoggedIn, function(req, res, next){
User
.findOneAndUpdate({ _id: request.session.passport.user }, req.body.email)
.exec(function(err, user) {
if (err) return res.render(/* Your error template here */, {
err: err.message
};
return res.render('landing.ejs', {
user: user
});
});
}
}
Hope this helps!

How to use .save method in mongo?

app.put('/app/modify/:_id', function(req, res) {
Collection.findById(req.params._id, function (err, blog) {
if (err) res.send(err);
if (req.body.text1) blog.text1 = req.body.text1;
if (req.body.text2) blog.text2 = req.body.text2;
if (req.body.text3) blog.text3 = req.body.text3;
if (req.body.text4) blog.text4 = req.body.text4;
if (req.body.text5) blog.text5 = req.body.text5;
Collection.save( function (err) {
if (err) send (err);
res.json({message: 'Blog Post Updated!'});
});
});
});
Taken help from this - PUT and DELETE - RESTful API Express MongoDB Mongoose
But getting error- http://localhost:8080/app/modify/59203c7d9532c34903000002 net::ERR_EMPTY_RESPONSE and Node server stops with an error 'Collection.save is not a function'.
Try it...
app.put('/app/modify/:_id', function(req, res) {
Collection.findById(req.params._id, function (err, blog) {
if (err) res.send(err);
if (req.body.text1) blog.text1 = req.body.text1;
if (req.body.text2) blog.text2 = req.body.text2;
if (req.body.text3) blog.text3 = req.body.text3;
if (req.body.text4) blog.text4 = req.body.text4;
if (req.body.text5) blog.text5 = req.body.text5;
blog.save( function (err,response) {
if (err) res.json(err);
res.json({message: 'Blog Post Updated!'});
});
});
});

RESTful API singular route with a single object to retrive and update (options parameters)

Hi i'm stucked trying to create a route in the RESTful API server in express.
I've configured other routes and now i need to configure an ('/options) or ('/profile') singular route where there is only one object to retrive and update.
Basically i need to do the same of the json-server module in the Singular routes section.
So when i visit the /options endpoint i got the predefined object with this schema
{
tax: Number,
inps: Number,
ritenuta: Number,
banca: {
nome: String,
iban: String
}
}
to update.
Here's my actual routes for /options:
var Option = require('../models/option');
var express = require('express');
var router = express.Router();
router.route('/options')
.get(function(req, res) {
Option.find(function(err, options) {
if (err) {
return res.send(err);
}
res.json(options);
});
})
.post(function(req, res) {
var option = new Option(req.body);
option.save(function(err) {
if (err) {
return res.send(err);
}
res.send({message: 'Option Added'});
});
});
// Save an option
router.route('/options/:id').put(function(req, res) {
Option.findOne({ _id: req.params.id}, function(err, option) {
if (err) {
return res.send(err);
}
for (prop in req.body) {
option[prop] = req.body[prop];
}
option.save(function(err) {
if (error) {
return res.send(err);
}
res.json({message: 'Option updated!'})
});
});
});
// Retrive an option
router.route('/options/:id').get(function(req, res) {
Option.findOne({ _id: req.params.id }, function(err, option) {
if (err) {
return res.send(error);
}
res.json(option);
});
});
// Delete an option
router.route('/options/:id').delete(function(req, res) {
Option.remove({ _id: req.params.id}, function(err, option) {
if (err) {
return res.send(err);
}
res.json({message: 'Option deleted!'});
});
});
module.exports = router;
but it's much complicated. It should be simpler. In fact, in this case i need to get all the options, get the id of options[0] and make a call with the id as params to retrive the object and update.
Any suggestions please?

Express Router CRUD API. Cannot DELETE

Well, I'm reading the MEAN Machine book and following it's examples. I'm trying to figure out what's wrong with my code so it won't make any DELETE request. GET, PUT and POST works as should.
I have this code on my server.js:
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization');
next();
});
var apiRouter = express.Router();
apiRouter.route('/users/:user_id')
.get( function (req, res) {
User.findById( req.params.user_id, function (err, user) {
if (err) res.send (err);
res.json(user);
});
})
.put( function (req, res) {
User.findById(req.params.user_id, function (err, user) {
if (err) res.send(err);
if (req.body.name) user.name = req.body.name;
if (req.body.username) user.username = req.body.username;
if (req.body.password) user.password = req.body.password;
user.save( function (err){
if (err) send (err);
res.json({message: 'User updated'});
});
})
.delete( function (req, res) {
User.remove({
_id: req.params.user_id
}, function (err, user) {
if (err) return res.send(err);
res.json({ message: 'Deleted' });
});
});
});
I have a set of users the Modulus MongoDB database and, when I try to use POSTMAN with localhost:8080/api/users/5610e5576d827dc41fb8e6e, POSTMAN says
Cannot DELETE /api/users/5610e5576d827dc41fb8e6e
while my Node server with Morgan says
DELETE /api/users/5610e5576d827dc41fb8e6e 404
Why I'm getting a 404? What Am I doing wrong?
Full code
You've placed closing brackets of put() in wrong place. So you're defining your delete router inside the put() router:
This is your code after proper indentation:
.put( function (req, res) {
User.findById(req.params.user_id, function (err, user) {
if (err) res.send(err);
if (req.body.name) user.name = req.body.name;
if (req.body.username) user.username = req.body.username;
if (req.body.password) user.password = req.body.password;
user.save( function (err){
if (err) send (err);
res.json({message: 'User updated'});
});
})
.delete( function (req, res) { // <===== defined inside 'put',
User.remove({
_id: req.params.user_id
}, function (err, user) {
if (err) return res.send(err);
res.json({ message: 'Deleted' });
});
});
})
So, just move the delete router outside of put router callback

Resources