0

The following is using nodejs, expressjs, mongodb. On the live site it is using mongolab. I am making a POST request from the front end to the server, and the server handles the request by deleting a single matching record from the database. The server work (done in ExpressJS is as follows:

var removeStuff = req.body.removeStuff;
var currentId = req.user._id;
var currentEmail = req.user.email;

myStuff.findOne({
  $and: [
      { $or: [{stuff: removeStuff}] },
      { $or: [{apid:currentId},{apiemail:currentEmail}] }
  ]
}, function (err, currentStuff) {
  currentStuff.remove();
  res.send('Stuff was removed from database...')
});

What's really strange is that this works perfectly for the site when I'm running it on localhost. But when it's live, making the request removes ALL records from the database.

maudulus
  • 10,627
  • 10
  • 78
  • 117
  • That's not possible unless it's a bug with mongoose. There must be code elsewhere that is the offending code. You're calling `.remove()` on the document which has no impact on the collection. – chrisbajorin Oct 14 '15 at 18:58
  • Hmmm I've been looking all over for bugs...again it works perfectly on the localhost, so maybe it could be with mongoose? I saw that previously there was a bug of this sort but it was in 2013 https://github.com/Automattic/mongoose/issues/1649 – maudulus Oct 14 '15 at 19:09
  • 1
    `.remove()` calls `collection.remove(obj)` where `obj` is the entire document you are calling it on. So the only possible match is itself(since it includes it's id). take a look at what it does [here](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L637-L686) for the call itself, and [here](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L585-L609) for an explanation of what it uses as a match. (check which version you are using as well) – chrisbajorin Oct 14 '15 at 20:05

1 Answers1

0

Ok, I got it. I'm not sure exactly why the original doesn't work, but I found that in this StackOverflow question someone answered a similar question. What they did was along the lines of:

var removeStuff = req.body.removeStuff;
var currentId = req.user._id;
var currentEmail = req.user.email;

myStuff.findOneAndRemove({
  $and: [
      { $or: [{stuff: removeStuff}] },
      { $or: [{apid:currentId},{apiemail:currentEmail}] }
  ]
}, function (err) {
  res.status(200).send("it worked...");
});
Community
  • 1
  • 1
maudulus
  • 10,627
  • 10
  • 78
  • 117