0

I'm trying to select/delete entries from my mongodb via node.js and mongodb-wrapper. I get the id of the entry as a string via a http request. Then I want to delete the entry with the specific id.

app.delete('/posts/:id', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
db.posts.remove({"_id": req.params.id}, function(err) {
    if (err) return res.send(err.message, 500); // server error
    res.send(200);
  })
res.send("ok");
});

But this is not working. I already tried several ways but nothing deletes the entry. I have red something that I must convert the string into a ObjectId but until now I didn't found anything how to do this via mongodb-wrapper.

royhowie
  • 11,075
  • 14
  • 50
  • 67
soupdiver
  • 3,504
  • 9
  • 40
  • 68
  • [This][1] question might be able to help you out. [1]: http://stackoverflow.com/questions/4902569/node-js-mongodb-select-document-by-id-node-mongodb-native – Tim Gautier Apr 10 '12 at 18:49
  • I already was there... but I did look again and a quite deeper and found my problem :) – soupdiver Apr 10 '12 at 19:10

1 Answers1

1

By using: {"_id": req.params.id} you are querying for a string rather than an objectId. You need to create an ObjectId from the string to use it:

var ObjectID = require('mongodb').ObjectID;
var oid = new ObjectID(req.params.id);

be aware that this will throw an error if the data in req.params.id can not be converted to a valid ObjectID.

mpobrien
  • 4,922
  • 1
  • 33
  • 35