handless
handless

Reputation: 311

mongoose remove not working [findByIdAndRemove]

I try to remove object by id , but get error "[TypeError: Cannot read property '$set' of undefined]" what can be wrong?

var remove = function(req, res, next) {

var id = req.urlParams.id ;

req.urlParams.model.findByIdAndRemove(id,function(err, doc){
console.log(err);
if (err) { return sendError(res,err) }

var data = JSON.stringify(req.body);
...
}

id is initialized and object with that id exist

Upvotes: 1

Views: 10274

Answers (4)

Akash Maurya
Akash Maurya

Reputation: 1

Remove using id:

Model.findByIdAndRemove(id).exec();

Upvotes: 0

Pranay Reddy
Pranay Reddy

Reputation: 1

var id = mongoose.Types.ObjectId((req.urlParams.id).trim());

Upvotes: 0

KOO
KOO

Reputation: 61

I don't know your whole code but, if your goal is remove object that _id has req.urlParams.id, following code would help you.

var remove = function(req, res, next) {
yourModel.remove({_id: req.urlParams.id},function(err, doc){
console.log(err);

if (err) { return sendError(res,err) }
else{ //do something}
}

I have a question : console.log(req.urlParams.id) work?
if you could type your code detail, I can help you more

Upvotes: 0

Ben Hughes
Ben Hughes

Reputation: 1539

It seems a little strange that you're looking for your mongoose model in the urlParams. I would have expected something more like

function remove(req, res, model, next){
    model.findByIdAndRemove(req.params.id, function(err)....
}

Upvotes: 3

Related Questions