1

I am new to NodeJS.I was trying to create an api which will delete multiple users in a single go.I know how to delete single rows/user but getting stuck at multiple ones.

This is what i have done for a single user

var User = require('../models/User');
var moment = require('moment');
var jwt = require('jwt-simple');
var config = require('../config');


function createJWT(user) {
  var payload = {
    sub: user._id
    , iat: moment().unix()
    , exp: moment().add(14, 'days').unix()
  };
  return jwt.encode(payload, config.TOKEN_SECRET);
}

exports.createUser = function (req, res, next) {
  var user = new User(req.userData);
  user.save(function (err, result) {
    if (err) {
      res.status(500).send({
        message: err.message
      });
    }
    if(result.status == 'unverified')
      return next();
    else
      res.send({
        token: createJWT(result),
        user : user
      });
  });
};

exports.removeUser = function(req, res){
  User.findById(req.params.id).remove(function(){
    res.redirect('/');
  });
};

Can anyone help me out with this.

3
  • You could create a loop depending on the number of params given and then execute the query (slightly modified tho) which you've already used. Commented Oct 16, 2017 at 11:52
  • You can delete all users by dropping the database :P But in all seriousness, if you want to delete them by ID, you should just use a loop and call the function to delete a single user. Commented Oct 16, 2017 at 11:55
  • Or use User.remove() which actually takes a query in argument. If that is the question then it's been answered long ago. Commented Oct 16, 2017 at 11:56

3 Answers 3

6

There is a simple way to do it.You can use 'IN' operator directly on model

User.remove({'_id':{'$in':[array_of_id]}})

Note: You shouln't use loop for delele, it's not a good practice.

Mongoose - Model.remove

Sign up to request clarification or add additional context in comments.

2 Comments

Whats the best way to delete multiple Users in node if you can help me out
Before deleting, you can create an array of user_id's which needs to be deleted. If it depends on some condition then you can first query a database for such list. this will be lightweight.
1

suppose you have an array of userIDs say uidArr

first method

User.remove({'_id':{'$in':uidArray}})

second method using async flow library

const async=require('async');
async.forEach(uidArray, function (uid, callback) {
  User.findById(uid).remove(function(err){
  err ? callback(err) : callback(null);
  });
  },function(err) {
    if (err)
      return res.status(400).send(err);
    else
     return res.redirect('/');
  });

2 Comments

I didnt think you can pass an array to req.params, or at least I don't know how. You can pass it through a post body, and retrieve it from req.body.array. But, assuming you get an array or user ids, iterating through it to delete each one makes sense to me.
Right..we can't pass array to req.params,though we can pass through req.query or req.body.. so i updated the answer removing the confusion.
0

By the look of it, I am guessing you are using mongoose?

Anyway if you use User.remove({_id: req.params.id}) where the object inside the remove is the query that will apply. req.params.id is a array of user_ids.

Remove in mongo removes all records that match your query. This also applies if you are using the mongo driver with using db.User.remove({}). Btw according to the docs you could use deleteMany to run your query

UPDATE Sagar's solution is absolutely correct. If you are looking into deleting multiple IDs you could use the $in and if you're looking into deleting records in different attributes you can use the $or query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.