简体   繁体   中英

Call multiple modules in route Express, Nodejs

This is the first time I create an API. I've tried to delete the user items once, the user is removed. I was able to delete the user but i didn't succeed to delete the items.

User.js

express = require('express');
User = require('./user');
Item = require('../item');
router = express.Router();

User.findByIdAndRemove(req.params.id, function(err, user) {
  if (err) {
    return res.status(500).send('User not found by id.');
  }
  Item.deleteMany(user._id, function(err, item) {
    if (err) {
      return res.status(500).send('Item is not found');
    }
    return res.status(200).send(user, item);
  });
});

Is there a way to achieve this? because I have a feeling that I'm doing it the wrong way.

Thanks!

It looks like you are not defining the actual routes -- you need

router.route('/').post(function(req, res){ ... });

You should also include the body parser to get the parameters out of the request

var bodyParser = require('body-parser');
app.use(bodyParser.json());
var parseUrlencoded = bodyParser.urlencoded({extended: false});

The code you have for User methods will look more like the below block. You can change '/' to the URL path you would rather have the api respond to and can change the code from being in .post to .delete depending on what method you want to respond to

route.route('/')
  .post(parseUrlencoded, function(req, res) {
    // code to respond to 'post' methods
    if (!req.params.id) {
      return res.send('id not sent')
    }

    User.findByIdAndRemove(req.params.id, function(err, user) {
      if (err) {
        return res.status(500).send('User not found by id.');
      }
      Item.deleteMany(user._id, function(err, item) {
        if (err) {
          return res.status(500).send('Item is not found');
        }
        return res.status(200).send(user, item);
      });
    });
  })
  .delete(parseUrlencoded, function(req, res) {
    // code to respond to 'delete' method
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM