Monday, 29 May 2017

POST and GET from subdirectory

Hello guys and thanks for any help you can give me, im very new working with node and monogDB so this the first time i try to create an api. the idea is to POST element in a subroute example: api/application/:applicationID/contacts.

index.js

'use strict'

const app = require('../ticket/index.js');
const bodyParser = require('body-parser');
const applicationsCtrl = require('./applicationsCtrl');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/api/applications/:applicationid/contactsapp', applicationsCtrl.getAllContactsApp);
app.post('/api/applications/:applicationid/contactsapp', applicationsCtrl.createContactsApp);

Ctrl

function getAllContactsApp(req, res){
  Conctactsapp.find({}, (err, contactapp)=>{
    if(err){
      return res.status(500).send({message: 'Error al resalizar peticion'})
    }else if(!contactapp){
      return res.status(404).send({message: 'El producto no existe'})
    }else{
      res.status(200).send({contactapp});
    }
  });
}

function createContactsApp(req, res){
  let applicationId = req.params.applicationid;
  let contactapp = new Conctactsapp();
  contactapp.fullname = req.body.fullname;
  contactapp.avatar = req.body.avatar;
  contactapp.nickname = req.body.nickname;
  contactapp.company = req.body.company;
  contactapp.jobTitle = req.body.jobTitle;
  contactapp.email = req.body.email;
  contactapp.phone = req.body.phone;
  contactapp.sex = req.body.sex;
  contactapp.country = req.body.country;
  contactapp.channel = req.body.channel;
  contactapp.website_url = req.body.website_url;
  contactapp.linkedin_url = req.body.linkedin_url;
  contactapp.xing_url = req.body.xing_url;
  contactapp.notes = req.body.notes;
  contactapp.active = req.body.active;

  contactapp.save((err, contactappStored) =>{
    if(err){
      res.status(500).send('Error: ' + err);
    }else{
      res.status(200).send({contactapp: contactappStored});
    }
  });

}

my problem is that when i try to add a new contact that an specific application using the application id, what is does is that add the contact to all the application on the route api/applications and not to the api/application/:applicationID.



via Miguel Angel Gomez

No comments:

Post a Comment